在 HTML5 和 JavaScript 中循环遍历 localStorage [英] Looping through localStorage in HTML5 and JavaScript
问题描述
所以,我想我可以像普通对象一样循环遍历 localStorage,因为它有长度.我怎样才能遍历这个?
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.setItem(1,'Lorem');
localStorage.setItem(2,'Ipsum');
localStorage.setItem(3,'Dolor');
如果我执行 localStorage.length
它返回 3
这是正确的.所以我假设 for...in
循环会起作用.
If I do a localStorage.length
it returns 3
which is correct. So I'd assume a for...in
loop would work.
我在想:
for (x in localStorage){
console.log(localStorage[x]);
}
但无济于事.有什么想法吗?
But no avail. Any ideas?
我的另一个想法是
localStorage.setItem(1,'Lorem|Ipsum|Dolor')
var split_list = localStorage.getItem(1).split('|');
for...in
在其中起作用.
推荐答案
您可以使用 key
方法.localStorage.key(index)
返回第 index
个键(顺序是实现定义的,但在您添加或删除键之前保持不变).
You can use the key
method. localStorage.key(index)
returns the index
th key (the order is implementation-defined but constant until you add or remove keys).
for (var i = 0; i < localStorage.length; i++){
$('body').append(localStorage.getItem(localStorage.key(i)));
}
如果顺序很重要,您可以存储一个 JSON 序列化数组:
If the order matters, you could store a JSON-serialized array:
localStorage.setItem("words", JSON.stringify(["Lorem", "Ipsum", "Dolor"]));
规范草案声称任何支持 结构化克隆 可以是一个值.但这似乎尚不支持.
The draft spec claims that any object that supports structured clone can be a value. But this doesn't seem to be supported yet.
要加载数组,添加到它,然后存储:
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));
这篇关于在 HTML5 和 JavaScript 中循环遍历 localStorage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!