在 HTML5 和 JavaScript 中循环遍历 localStorage
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3138564/
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
Looping through localStorage in HTML5 and JavaScript
提问by Oscar Godson
So, I was thinking I could just loop through localStorage like a normal object as it has a length. How can I loop through this?
所以,我想我可以像普通对象一样循环遍历 localStorage,因为它有长度。我怎样才能遍历这个?
localStorage.setItem(1,'Lorem');
localStorage.setItem(2,'Ipsum');
localStorage.setItem(3,'Dolor');
If I do a localStorage.lengthit returns 3which is correct. So I'd assume a for...inloop would work.
如果我做localStorage.length它返回3这是正确的。所以我假设一个for...in循环会起作用。
I was thinking something like:
我在想这样的事情:
for (x in localStorage){
console.log(localStorage[x]);
}
But no avail. Any ideas?
但无济于事。有任何想法吗?
The other idea I had was something like
我的另一个想法是
localStorage.setItem(1,'Lorem|Ipsum|Dolor')
var split_list = localStorage.getItem(1).split('|');
In which the for...indoes work.
其中for...in确实有效。
回答by Matthew Flaschen
You can use the keymethod. localStorage.key(index)returns the indexth key (the order is implementation-defined but constant until you add or remove keys).
您可以使用该key方法。 localStorage.key(index)返回第indexth 个键(顺序是实现定义的,但在您添加或删除键之前是不变的)。
for (var i = 0; i < localStorage.length; i++){
$('body').append(localStorage.getItem(localStorage.key(i)));
}
If the order matters, you could store a JSON-serialized array:
如果顺序很重要,您可以存储一个 JSON 序列化数组:
localStorage.setItem("words", JSON.stringify(["Lorem", "Ipsum", "Dolor"]));
The draft spec claims that any object that supports structured clonecan be a value. But this doesn't seem to be supported yet.
规范草案声称任何支持结构化克隆的对象都可以是一个值。但这似乎尚未得到支持。
EDIT: To load the array, add to it, then store:
编辑:要加载数组,添加到它,然后存储:
var words = JSON.parse(localStorage.getItem("words"));
words.push("hello");
localStorage.setItem("words", JSON.stringify(words));
回答by Putra Ardiansyah
The simplest way is:
最简单的方法是:
Object.keys(localStorage).forEach(function(key){
console.log(localStorage.getItem(key));
});
回答by miksiii
In addition to all the other answers, you can use $.eachfunctionfrom the jQuery library:
除了所有其他答案之外,您还可以使用jQuery 库中的$.each函数:
$.each(localStorage, function(key, value){
// key magic
// value magic
});
Eventually, get the object with:
最终,使用以下命令获取对象:
JSON.parse(localStorage.getItem(localStorage.key(key)));
JSON.parse(localStorage.getItem(localStorage.key(key)));
回答by jtblin
This works for me in Chrome:
这在 Chrome 中对我有用:
for(var key in localStorage) {
$('body').append(localStorage.getItem(key));
}
回答by Steve Isenberg
Building on the previous answer here is a function that will loop through the local storage by key without knowing the key values.
建立在前面的答案的基础上是一个函数,它将在不知道键值的情况下通过键循环遍历本地存储。
function showItemsByKey() {
var typeofKey = null;
for (var key in localStorage) {
typeofKey = (typeof localStorage[key]);
console.log(key, typeofKey);
}
}
If you examine the console output you will see the items added by your code all have a typeof string. Whereas the built-in items are either functions { [native code] } or in the case of the length property a number. You could use the typeofKey variable to filter just on the strings so only your items are displayed.
如果您检查控制台输出,您将看到代码添加的项目都有一个 typeof 字符串。而内置项目要么是函数 { [native code] },要么是长度属性的数字。您可以使用 typeofKey 变量仅对字符串进行过滤,以便仅显示您的项目。
Note this works even if you store a number or boolean as the value as they are both stored as strings.
请注意,即使您将数字或布尔值存储为值,这也有效,因为它们都存储为字符串。
回答by StarTraX
All of these answers ignore the differences between the implementations of localStorage across browsers. Contributors in this domain should heavily qualify their responses with the platforms they are describing. One browser-wide implementation is documented at https://developer.mozilla.org/en/docs/Web/API/Window/localStorageand, whilst very powerful, only contains a few core methods. Looping through the contents requires an understanding of the implementation specific to individual browsers.
所有这些答案都忽略了跨浏览器的 localStorage 实现之间的差异。这个领域的贡献者应该用他们所描述的平台来充分限定他们的回答。https://developer.mozilla.org/en/docs/Web/API/Window/localStorage记录了一种浏览器范围的实现 ,虽然非常强大,但仅包含一些核心方法。循环浏览内容需要了解特定于各个浏览器的实现。
回答by Shayan
localStorageis an Object.
We can loop through it with JavaScript for/in Statementjust like any other Object.
我们可以像任何其他对象一样使用JavaScript for/in Statement循环遍历它。
And we will use .getItem()to access the value of each key (x).
我们将使用.getItem()来访问每个键 (x) 的值。
for (x in localStorage){
console.log(localStorage.getItem(x));
}

