2013-03-16 26 views
0
格式化

您好,我目前正在運行在我的JavaScript函數稱爲「保存」,其具有的功能:更改在Javascript

function save(){ 

var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || []; 

var newItem = {}; 
var num = document.getElementById("num").value; 

newItem[num] = { 
    "methv": document.getElementById("methv").value 
    ,'q1': document.getElementById("q1").value, 
    'q2':document.getElementById("q2").value, 
    'q3':document.getElementById("q3").value, 
    'q4':document.getElementById("q4").value, 
    'comm':document.getElementById("comm").value 
}; 


oldItems.push(newItem); 

localStorage.setItem('itemsArray', JSON.stringify(oldItems)); 

,目前的這個格式出來是這樣的:

[{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}}] 

有什麼辦法,我可以將它更改爲一個格式是這樣的:

{1173627548,不知道, - , - ,U, - ,} 感謝

+0

當然,你可以把它寫這樣的,但這不會再被JSON。你會如何解析它? – 2013-03-16 16:03:45

+0

所以你想剝離屬性名稱,結構和引號?正如提到的那樣,這不是JSON,如果格式發生變化,您將無法從中取回數據。你也不會寫任何有逗號的東西,而不會以某種方式逃脫。如果你想這樣做,你也可以用自己的函數來編寫字符串。 – Dave 2013-03-16 16:06:35

回答

1

所有您需要做的是使用,而不是一個對象數組:

newItem = [ 
    num, 
    document.getElementById('methv').value, 
    document.getElementById('q1').value, 
    document.getElementById('q2').value, 
    document.getElementById('q3').value, 
    document.getElementById('q4').value, 
    document.getElementById('comm').value 
];