如何从javascript中获取存储在html 5本地存储中的项目列表?
答
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.
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);
}
这将输出:
testing 3
testing 2
testing 1
test3 => testing 3
test2 => testing 2
test => testing 1
答
由于localStorage是字符串的键值,只需使用JSON对其进行序列化,并在想要检索它时将其反序列化。
localStorage.setItem("bar", JSON.stringify([1,2,3]));
var foo = localStorage.getItem("bar");
JSON.parse(foo);
// returns [1,2,3]
答
localStorage的是参照对象window.St ORAGE,所以ü可以用它作为对方的对象:
得到物品的排列与jQuery
Object.keys(localStorage)
获取长度
Object.keys(localStorage).length
迭代
$.each(localStorage, function(key, value){
.....
})
答
可以使用Object.assign()
:
var data = Object.assign({}, localStorage)
说什么?在cookie中? – Neal 2011-03-23 19:45:36