views:

347

answers:

1

So, I was thinking I could just loop through localStorage like a normal object as it has a length. How can I loop through this?

localStorage.setItem(1,'Lorem');
localStorage.setItem(2,'Ipsum');
localStorage.setItem(3,'Dolor');

If I do a localStorage.length it returns 3 which is correct. So I'd assume a for...in loop would work.

I was thinking something like:

for (x in localStorage){
    $('body').append(localStorage[x]);
}

But no avail. Any ideas?

The other idea I had was something like

localStorage.setItem(1,'Lorem|Ipsum|Dolor')
var split_list = localStorage.getItem(1).split('|');

In which the for...in does work.

+3  A: 

You can use the key method. localStorage.key(index) returns the indexth key (the order is implementation-defined but constant until you add or remove keys).

for (var i = 0; i < localStorage.length; i++){
    $('body').append(localStorage.getItem(localStorage.key(i)));
}

If the order matters, you could store a JSON-serialized array:

localStorage.setItem("words", JSON.stringify(["Lorem", "Ipsum", "Dolor"]));

The draft spec claims that any object that supports structured clone can be a value. But this doesn't seem to be supported yet.

EDIT: To load the array, add to it, then store:

var words = JSON.parse(localStorage.getItem("words"));
words.push("hello");
localStorage.setItem("words", JSON.stringify(words));
Matthew Flaschen
Thanks a lot! This is just what I was looking for. Im going to look into the JSON thing you sent also. Thatd be perfect. It's for a Baby Names Offline HTML5 iOS app.
Oscar Godson
Quick question, how would I add to that JSON? Like, how would I add "hello" after "Dolor"?
Oscar Godson
@Oscar, I gave an example above. Basically, get, parse, modify the array, stringify, set.
Matthew Flaschen
you rock, just looking at, it should work. Is there a reason I should use parse and not eval? I'm using eval now to get it from a string, but is parse better/faster?
Oscar Godson
@Oscar, `parse` is more secure because it protects you from code execution. And often, it's also much faster. See http://blog.mozilla.com/webdev/2009/02/12/native-json-in-firefox-31/
Matthew Flaschen