How do I store an array in localStorage? [duplicat

2018-12-31 05:33发布

This question already has an answer here:

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?

7条回答
步步皆殇っ
2楼-- · 2018-12-31 05:46

Another solution would be to write a wrapper that store the array like this:

localStorage.setItem('names_length', names.length);
localStorage.setItem('names_0', names[0]);
localStorage.setItem('names_1', names[1]);
localStorage.setItem('names_' + n, names[n]);

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 :)

查看更多
余生请多指教
3楼-- · 2018-12-31 05:48

Just created this:

https://gist.github.com/3854049

//Setter
Storage.setObj('users.albums.sexPistols',"blah");
Storage.setObj('users.albums.sexPistols',{ sid : "My Way", nancy : "Bitch" });
Storage.setObj('users.albums.sexPistols.sid',"Other songs");

//Getters
Storage.getObj('users');
Storage.getObj('users.albums');
Storage.getObj('users.albums.sexPistols');
Storage.getObj('users.albums.sexPistols.sid');
Storage.getObj('users.albums.sexPistols.nancy');
查看更多
几人难应
4楼-- · 2018-12-31 05:51

localStorage only supports strings. Use JSON.stringify() and JSON.parse().

var names = [];
names[0] = prompt("New member name?");
localStorage.setItem("names", JSON.stringify(names));

//...
var storedNames = JSON.parse(localStorage.getItem("names"));
查看更多
像晚风撩人
5楼-- · 2018-12-31 05:57

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).

查看更多
流年柔荑漫光年
6楼-- · 2018-12-31 05:58

Use JSON.stringify() and JSON.parse() as suggested by no! This prevents the maybe rare but possible problem of a member name which includes the delimiter (e.g. member name three

查看更多
余欢
7楼-- · 2018-12-31 05:59
bars).

查看更多
登录 后发表回答