Java Reference
In-Depth Information
converted to a string and stored as a string. For example, let's say you want to store the user's age in
local storage. You can easily do so like this:
localStorage.age = 35;
As you rightly suspect, this creates a key/value pair of age/35 . But 35 was converted to a string
before it was stored in local storage. Therefore, when you retrieve the value associated with the age
key, you have the string of 35 :
var age = localStorage.age;
alert(typeof age); // string
This means that to use age in any mathematic calculations, you need to convert it to a number.
That's easy enough to fix:
var age = parseInt(localStorage.age, 10);
But what about more complex objects? Consider the following object as an example:
var johnDoe = {
firstName: "John",
lastName: "Doe",
age: 35
};
This johnDoe object represents an individual person named John Doe, and he is 35 years old. We
want to save this object in local storage, so we assign it as the value to the person key, like this:
localStorage.person = johnDoe;
But there's a problem here: The person object cannot be reasonably converted into a string.
When you assign a value or object to a key, its toString() method is automatically called to convert
it to a string. For primitive types like Number and Boolean , we get the string representation of that
value. But by default, an object's toString() method returns " [object Object] ". Therefore in the
preceding example, the string " [object Object] " is stored in localStorage.person :
var savedPerson = localStorage.person;
alert(typeof savedPerson); // string
alert(savedPerson); "[object Object]"
This sounds like a huge limitation (and it is!), but we can serialize objects into JSON and parse them
back into actual objects. Therefore, we can write this:
localStorage.person = JSON.stringify(johnDoe);
var savedPerson = JSON.parse(localStorage.person);
This code serializes the johnDoe object and stores the resulting JSON with the person key. Then,
when you need to retrieve and use that information, you deserialize the JSON using JSON.parse()
and assign the resulting object to the savedPerson variable. Now we can store just about anything
we need to in local storage, and we have a ton of space to store it in!
Search WWH ::




Custom Search