This question already has an answer here:
- Storing Objects in HTML5 localStorage 27 answers
If I didn't need localStorage, my code would look like this:
var names=new Array();
names[0]=prompt("New member name?");
This works. However, I need to store this variable in localStorage and it's proving quite stubborn. I've tried:
var localStorage[names] = new Array();
localStorage.names[0] = prompt("New member name?");
Where am I going wrong?
The
localStorage
andsessionStorage
can only handle strings. You can extend the default storage-objects to handle arrays and objects. Just include this script and use the new methods:Use
localStorage.setObj(key, value)
to save an array or object andlocalStorage.getObj(key)
to retrieve it. The same methods work with thesessionStorage
object.If you just use the new methods to access the storage, every value will be converted to a JSON-string before saving and parsed before it is returned by the getter.
Source: http://www.acetous.de/p/152