您好,我对javascipt很陌生,所以请清楚地解释一下。我目前正在运行一个php页面,其中包括:

<input type="text" id="data"/>

<script>
document.getElementById("data").value = localStorage.getItem('itemsArray');
</script>


此items数组包含这样保存的对象:

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.ge27548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}}]tElementById("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":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}}]

无论如何,我可以拆分数据,以便一次像循环之类的东西来操纵它。例如:

第一次:

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


下一个:

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


等等

谢谢。

最佳答案

数据已经以数组形式返回,您可以使用标准的for循环进行遍历。但是,您将需要首先对其进行解析,以便拥有一个可以使用标准对象方法访问的对象。

例如:

var allItems = JSON.parse(localStorage.getItem('itemsArray')) || [];
for(var i = 0; i < allItems.length; i++) {
  var item = allItems[i];
  console.log('Current item: %o', item);
  // do whatever you want to it, etc.
}

09-17 23:10