Kyl*_*yle 39 html javascript html5
如何从javascript获取存储在html 5本地存储中的项目列表?
KJY*_*葉家仁 56
来自HTML5参考:
与其他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);
}
Run Code Online (Sandbox Code Playgroud)
这将输出:
testing 3
testing 2
testing 1
test3 => testing 3
test2 => testing 2
test => testing 1
Run Code Online (Sandbox Code Playgroud)
Ric*_*tta 25
localStorage是对象window.Storage的引用,所以你可以将它作为彼此的对象使用:
获取一系列项目
Object.keys(localStorage)
Run Code Online (Sandbox Code Playgroud)
得到长度
Object.keys(localStorage).length
Run Code Online (Sandbox Code Playgroud)
用jquery迭代
$.each(localStorage, function(key, value){
.....
})
Run Code Online (Sandbox Code Playgroud)
你可以使用Object.assign()
:
var data = Object.assign({}, localStorage)
Run Code Online (Sandbox Code Playgroud)