gpt4 book ai didi

javascript - 拆分文本字段中的数据

转载 作者:行者123 更新时间:2023-11-28 20:35:43 26 4
gpt4 key购买 nike

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

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

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

此项目数组包含像这样保存的对象:

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":"不知道","q1":"-","q2":"-","q3":"U","q4": "-","comm":""}},{"1173627548":{"methv":"不知道","q1":"-","q2":"-","q3":"U ","q4":"-","comm":""}},{"1173627548":{"methv":"不知道","q1":"-","q2":"-", "q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"不知道","q1":"-","q2 ":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"不知道","q1": "-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"不知道","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":""}}

等等

谢谢。

最佳答案

您应该像 save() 方法在填充 oldItems 数组时所做的那样 JSON.parse() ,然后您可以循环生成的数组。

示例代码:

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

<script>
var myArray = JSON.parse(localStorage.getItem('itemsArray')) || [];
for (var i = 0; i < myArray.length; i++) {
var element = myArray[i];
// Do something with element.
}
</script>

关于javascript - 拆分文本字段中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15434539/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com