0

I'm writing a small game in Javascript. So far everything works perfectly, except I have no idea how localStorage works. I've looked everywhere for a decent explanation but everything is going way over my head.

I have an object and a number of variables that I want to store, all numbers.

land = {
total:150000000,
owned:1,
cost: 110,
housing: 14
};

As well as these variables,

var seconds = 0;
var minutes = 0;
var hours = 0;
var days = 0;
var years = 0;

Can anyone please point me in the right direction on how to save and load these objects/variables from localStorage?! Any help at all is greatly appreciated.

1 Answers1

1

Local storage simply provides a way to store key value pairs. For example you can write something like localStorage.myName = 'Ali' And layer when you call

localStorage.myName

You'll get 'Ali'

You can also store your object as is by saying

localStorage.land = land

But in this case your object will be stored as a string, so to retrieve it you can write something like

var myObj = JSON.parse(localStorage.land) 

Now myObj contains your land object.

And also note to store objects as strings you have to use JSON.stringify(yourObject)

Alizoh
  • 1,562
  • 1
  • 13
  • 16