jQuery 如何在html5的localStorage对象中存储数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19174525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to store array in localStorage Object in html5?
提问by Shakti Patel
How to store mycars array in localStorage Object in html5?
如何将 mycars 数组存储在 html5 的 localStorage 对象中?
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";
localStorage.mycars=?;
回答by scotty
localStorageis for key : valuepairs, so what you'd probably want to do is JSON.stringifythe array and store the string in the mycarskey and then you can pull it back out and JSON.parseit. For example,
localStorage是key : value成对的,所以你可能想要做的是JSON.stringify数组并将字符串存储在mycars键中,然后你可以把它拉回来JSON.parse。例如,
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";
localStorage["mycars"] = JSON.stringify(mycars);
var cars = JSON.parse(localStorage["mycars"]);
回答by Vinay Pratap Singh
Check his Link
检查他的链接
http://diveintohtml5.info/storage.html
http://diveintohtml5.info/storage.html
This is like a crash course for working with local storage also check this article from Mozilla Firefox
这就像使用本地存储的速成课程也可以从 Mozilla Firefox 查看这篇文章
http://hacks.mozilla.org/2009/06/localstorage/
http://hacks.mozilla.org/2009/06/localstorage/
here is the official documentation for local storage
这是本地存储的官方文档
http://dev.w3.org/html5/webstorage/
http://dev.w3.org/html5/webstorage/
Just For your problem, you can do it like this
只是为了你的问题,你可以这样做
localStorage only supports strings. Use JSON.stringify()and JSON.parse().
localStorage 仅支持字符串。使用JSON.stringify()和JSON.parse().
var mycars = [];
localStorage["mycars"] = JSON.stringify(carnames);
var storedNames = JSON.parse(localStorage["mycars"]);
回答by Parag Gangil
LocalStoragecan store strings and not arrays directly. Use some special symbol like '~'to concatenate the elements of array and save it as an array. When retrieving , using split('~')to get back the array.
LocalStorage可以直接存储字符串而不是数组。使用像'~'这样的特殊符号来连接数组的元素并将其保存为数组。检索时,使用split('~')取回数组。

