gpt4 book ai didi

JavaScript - 项目未添加到数组中

转载 作者:行者123 更新时间:2023-12-01 02:28:50 24 4
gpt4 key购买 nike

我已经做了jsFiddle 。下面是一些代码。

我的预期输出是

[{
"support_advice": [{
"id": "A",
"type": "checkbox",
"text": "",
"value": "A"
},
{
"id": "C",
"type": "checkbox",
"text": "",
"value": "C"
}
]
}]

但是我得到了

[{
"support_advice": [{
"id": "C",
"type": "checkbox",
"text": "",
"value": "C"
}]
}]

我认为 result[elem[i].name] = matches; 会添加另一个项目,而不是替换已有的项目

HTML

<form id="rn_QuestionSubmit">
<input name="support_advice" id="A" type="checkbox" value="A" checked>
<input name="support_advice" id="B" type="checkbox" value="B">
<input name="support_advice" id="C" type="checkbox" value="C" checked>
</form>

JavaScript

var elem = document.getElementById('rn_QuestionSubmit').elements;

var a = [];
var result = {};

for(var i = 0; i < elem.length; i++)
{
var matches = [];
var item = {};
item.id = elem[i].id;
item.type = elem[i].type;
if (elem[i].type === 'select-one') {
item.text = document.getElementById(elem[i].id).options[document.getElementById(elem[i].id).selectedIndex].text;
}
else {
item.text = '';
}

if (elem[i].type === 'radio' || elem[i].type === 'checkbox') {
if (document.getElementById(elem[i].id).checked) {

item.value = document.getElementById(elem[i].id).value;
matches.push(item);
result[elem[i].name] = matches;
}
}
else {
item.value = elem[i].value;
matches.push(item);
result[elem[i].name] = matches;
}
}

a.push(JSON.stringify(result));
console.log('['+a.join(',') + ']');
return('['+a.join(',') + ']');

最佳答案

这里可以清理很多不需要的代码...

var elem = document.getElementById('rn_QuestionSubmit').elements;

var a = [];
var result = {};

for(var i = 0; i < elem.length; i++)
{
var element = elem[i];
var item = {};
item.id = element.id;
item.type = element.type;
if (element.type === 'select-one') {
item.text = element.options[element.selectedIndex].text;
}
else {
item.text = '';
}

if (element.type === 'radio' || element.type === 'checkbox') {
if (element.checked) {
item.value = element.value;
if (result[element.name]) { result[element.name].push(item) } else { result[element.name] = [item]};
}
}
else {
item.value = elem[i].value;
if (result[element.name]) { result[element.name].push(item) } else { result[element.name] = [item]};
}
}

a.push(JSON.stringify(result));
console.log('['+a.join(',') + ']');
return('['+a.join(',') + ']');

您需要实际决定在每个元素上推送或创建一个新数组。

fiddle :https://jsfiddle.net/0jhyj4wv/

关于JavaScript - 项目未添加到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48479640/

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