如何从javascript中获取存储在html 5本地存储中的项目列表?

问题描述:

如何从javascript中获取存储在html 5本地存储中的项目列表?如何从javascript中获取存储在html 5本地存储中的项目列表?

+0

说什么?在cookie中? – Neal 2011-03-23 19:45:36

HTML5 reference

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 

这里是JSFiddle Demo

+0

在Chrome中为我工作,但Firefox 3.6抛出了错误“TypeError:null有无效的__iterator__值null” – Kyle 2011-03-23 19:58:08

+0

@Kyle它在firefox中很好用4.它昨天让我检查3.6 – kjy112 2011-03-23 19:59:48

+0

@Kyle即使Firefox支持localStorage ,它可以关闭。检查它是否打开。转到about:config并检查dom.storage.enabled是否设置为true。 – kjy112 2011-03-23 20:10:21

由于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){ 
    ..... 
}) 
+4

jQuery ?!捂脸。 'Object.keys(localStorage).forEach(key => console.log(localStorage [key]));' – c24w 2016-08-09 16:12:19

+0

有没有办法获取所有域的条目,而不是当前标签中的条目? – mins 2016-10-08 14:37:54

可以使用Object.assign()

var data = Object.assign({}, localStorage)