Javascript 如何从javascript获取存储在html 5本地存储中的项目列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5410745/
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 can I get a list of the items stored in html 5 local storage from javascript?
提问by Kyle
How can I get a list of the items stored in html 5 local storage from javascript?
如何从javascript获取存储在html 5本地存储中的项目列表?
回答by u476945
From HTML5 reference:
来自HTML5 参考:
Like other JavaScript objects, you can treat the localStorage object as an associative array. Instead of using the getItem() and setItem() methods, you can simply use square brackets.
与其他 JavaScript 对象一样,您可以将 localStorage 对象视为关联数组。您可以简单地使用方括号,而不是使用 getItem() 和 setItem() 方法。
localStorage.setItem('test', 'testing 1');
localStorage.setItem('test2', 'testing 2');
localStorage.setItem('test3', 'testing 3');
for(var i in localStorage)
{
console.log(localStorage[i]);
}
//test for firefox 3.6 see if it works
//with this way of iterating it
for(var i=0, len=localStorage.length; i<len; i++) {
var key = localStorage.key(i);
var value = localStorage[key];
console.log(key + " => " + value);
}
This will output:
这将输出:
testing 3
testing 2
testing 1
test3 => testing 3
test2 => testing 2
test => testing 1
Here is the JSFiddle Demo
回答by Richard Hutta
localStorage is reference to object window.Storage, so u can use it as each other object:
localStorage 是对对象 window.Storage 的引用,因此您可以将其用作其他对象:
Get array of items
获取项目数组
Object.keys(localStorage)
Get length
获取长度
Object.keys(localStorage).length
Iterate with jquery
用 jquery 迭代
$.each(localStorage, function(key, value){
.....
})
回答by Yukulélé
you can use Object.assign()
:
你可以使用Object.assign()
:
var data = Object.assign({}, localStorage)
回答by Mike Lewis
Since localStorage is key-value with strings, just serialize it with JSON, and deserialize it when you want to retrieve it.
由于 localStorage 是带有字符串的键值,因此只需将其序列化为 JSON,并在需要检索时反序列化即可。
localStorage.setItem("bar", JSON.stringify([1,2,3]));
var foo = localStorage.getItem("bar");
JSON.parse(foo);
// returns [1,2,3]
回答by Pavel Durov
What about:
关于什么:
Object.keys(localStorage).map(k => localStorage.getItem(k))