2011-03-23 51 views

回答

46

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

2

由於localStorage是字符串的鍵值,只需使用JSON對其進行序列化,並在想要檢索它時將其反序列化。

localStorage.setItem("bar", JSON.stringify([1,2,3])); 
var foo = localStorage.getItem("bar"); 
JSON.parse(foo); 
// returns [1,2,3] 
21

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

0

可以使用Object.assign()

var data = Object.assign({}, localStorage) 
相關問題