Javascript 如何在 localStorage 中存储数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3357553/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:18:05  来源:igfitidea点击:

How do I store an array in localStorage?

javascriptarrayshtmllocal-storage

提问by David

If I didn't need localStorage, my code would look like this:

如果我不需要 localStorage,我的代码将如下所示:

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:

这有效。但是,我需要将此变量存储在 localStorage 中,事实证明它非常顽固。我试过了:

var localStorage[names] = new Array();
localStorage.names[0] = prompt("New member name?");

Where am I going wrong?

我哪里错了?

回答by Dagg Nabbit

localStorageonly supports strings. Use JSON.stringify()and JSON.parse().

localStorage只支持字符串。使用JSON.stringify()JSON.parse()

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

//...
var storedNames = JSON.parse(localStorage.getItem("names"));

回答by Sebastian

The localStorageand sessionStoragecan only handle strings. You can extend the default storage-objects to handle arrays and objects. Just include this script and use the new methods:

localStoragesessionStorage只能处理字符串。您可以扩展默认存储对象来处理数组和对象。只需包含此脚本并使用新方法:

Storage.prototype.setObj = function(key, obj) {
    return this.setItem(key, JSON.stringify(obj))
}
Storage.prototype.getObj = function(key) {
    return JSON.parse(this.getItem(key))
}

Use localStorage.setObj(key, value)to save an array or object and localStorage.getObj(key)to retrieve it. The same methods work with the sessionStorageobject.

使用localStorage.setObj(key, value)保存一个数组或对象,并localStorage.getObj(key)对其进行检索。相同的方法适用于sessionStorage对象。

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.

如果您只是使用新方法访问存储,则每个值在保存和解析之前都会被转换为 JSON 字符串,然后由 getter 返回。

Source: http://www.acetous.de/p/152

资料来源:http: //www.acetous.de/p/152

回答by jayeff

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

使用JSON.stringify()JSON.parse()不建议!这可以防止可能罕见但可能出现的包含分隔符的成员名称问题(例如 member name three|||bars)。

回答by Klederson Bueno

Just created this:

刚刚创建了这个:

https://gist.github.com/3854049

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');

回答by Znarkus

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

消除了转换为 JSON 的开销,但是如果您需要删除元素会很烦人,因为您必须重新索引数组:)

回答by Lassi Kinnunen

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.

JSON 方法有效,在 ie 7 上你需要 json2.js,它可以完美运行,尽管有一条评论说否则有 localStorage。这似乎是最省事的最佳解决方案。当然,可以编写脚本来做与 json2 基本相同的事情,但这没什么意义。

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

至少在以下版本字符串中有 localStorage,但如上所述,您需要包含 json2.js,因为浏览器本身不包含它:4.0(兼容;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)(我会对此发表评论回复,但不能)。