HTML and CSS Reference
In-Depth Information
Finally, it's worth noting that if the key doesn't exist when you
call getItem , the storage API will return null. If you're planning
on using the storage API to initialise values, which is quite pos-
sible, you need to test for null before proceeding because it can
throw a pretty nasty spanner in the works if you try to treat null
as any other type of object.
Ways to access storage
As we've already seen, we can use setItem and getItem to
store and retrieve, respectively, but there are a few other
methods to access and manipulate the data being stored
in the storage object.
Using expandos
Expandos are a short and expressive way of setting and getting
data out of the storage object, and as both sessionStorage and
localStorage descend from the Web Storage API, they both sup-
port setting values directly off the storage object.
Using our example of storing a Twitter screen name, we can do
the same thing using expandos:
sessionStorage.twitter = '@rem';
alert( sessionStorage.twitter ); // shows @rem
Unfortunately the expando method of storing values also suf-
fers from the “stringifying” of values as we saw in the previous
example, with Bruce's video website.
Using the key method
The API also provides the key method, which takes an index
parameter and returns the key associated. This method is useful
to enumerate the data stored in the storage object. For exam-
ple, if you wanted to show all the keys and associated data, you
wouldn't particularly know what the keys were for each of the
data items, so loop through the length of the storage object and
use the key method to fi nd out:
for (var i = 0; i < sessionStorage.length; i++) {
alert( sessionStorage.key(i) + '=' +
¬ sessionStorage.getItem( sessionStorage.key(i) ) );
Search WWH ::

Custom Search