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?
Another solution would be to write a wrapper that store the array like this:
Removes the overhead of converting to JSON, but would be annoying if you need to remove elements, as you would have to re-index the array :)
Just created this:
https://gist.github.com/3854049
localStorage
only supports strings. UseJSON.stringify()
andJSON.parse()
.The JSON approach works, on ie 7 you need json2.js, with it it works perfectly and despite the one comment saying otherwise there is localStorage on it. it really seems like the best solution with the least hassle. Of course one could write scripts to do essentially the same thing as json2 does but there is little point in that.
at least with the following version string there is localStorage, but as said you need to include json2.js because that isn't included by the browser itself: 4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; BRI/2; NP06; .NET4.0C; .NET4.0E; Zune 4.7) (I would have made this a comment on the reply, but can't).
Use
JSON.stringify()
andJSON.parse()
as suggested by no! This prevents the maybe rare but possible problem of a member name which includes the delimiter (e.g. member namethree