2017-02-27 34 views
-1

我做了一些測試代碼,但它不起作用。使用JSON將數據保存在localstorage中

我推動localstorage上的數據,並從localstorag獲取數據e。之後,我改變了數據的值,並在localsorage上推送並添加數據。然後,我檢查了數據,我試圖用JSON.parse函數獲取數據。但是,它沒有工作。

這裏的a code

var temp1 = { 
    'temp1': true, 
    'test1': true 
}; 

var temp2 = { 
    'temp2': true, 
    'test2': true 
}; 

var temp3 = []; 
temp3.push(temp1); 
localStorage.setItem("testing", JSON.stringify(temp3)); 

var temp4 = localStorage.getItem("testing"); 
var temp5 = JSON.parse(temp4); 
for(var i=0; i<temp5.length; i++) 
{ 
    temp5[i].temp1 = false; 
} 
temp3.push(temp5); 

localStorage.setItem("testing", JSON.stringify(temp3)); 
var temp6 = localStorage.getItem("testing")); 
var temp7 = JSON.parse(temp6); 
for(var j=0; j<temp7.length; i++) 
{ 
    temp7[i].test1 = false; 
} 
temp3.push(temp7); 
localStorage.setItem("testing", JSON.stringify(temp3)); 
+0

歡迎來到堆棧溢出!請[編輯]你的問題直接在問題中顯示相關的代碼。 – nnnnnn

+0

請更明確。不要說「這行不通」,要清楚說明你想要做什麼,嘗試什麼以及發生了什麼。如果控制檯中有任何錯誤消息,請在發佈代碼之前修復它們,除非您確實不瞭解它們。 –

回答

1

有幾個小的語法錯誤由si2zle作爲mentioed,但主要的問題是,當你正在推動temp5temp7temp3,你實際上是在推動一個新的數組,而不是單個元素。

需要VAR處temp6 = localStorage.getItem( 「測試」))到每個單獨的元件推到temp3內部的for循環像這樣

for(var i=0; i<temp5.length; i++) 
{ 
    temp5[i].temp1 = false; 
    temp3.push(temp5[i]); 
} 
0

有在下面的代碼的錯誤:

for(var j=0; j<temp7.length; i++) 
{ 
    temp7[i].test1 = false; 
} 

有人J ++不我++和temp7 [j]的.test1 = FALSE;不temp7 [I]

0

有一個額外的 ')'; 也是,而「temp3.push(temp5);」它推動陣列中的陣列 這樣的:[{ 「temp1目錄」:真, 「測試1」:真},[{ 「temp1目錄」:假, 「測試1」:真}]]

which creates problem while parsing in the for loop. 

for(var j=0; j<temp7.length; i++) 
{ 
    temp7[i].test1 = false; 
} 

希望這幫助:)

相關問題