我在 for 循环中的这段代码中遇到了以下错误,但是当我给出 iput+=checkedBoxes[1].id staticaly 意味着它正在工作,请帮助,并且 for 循环中的警报正在与 s 一起使用
ERROR : Uncaught TypeError: Cannot read property 'id' of undefined at saveSign
function saveSign(){
alert('asd')
var iput =[];
var checkedBoxes = document.querySelectorAll('input[type=checkbox]');
for (var s=1;s<=checkedBoxes.length;s++){
iput+=checkedBoxes[s].id
}
console.log(iput)
}
最佳答案
问题与 for 循环的循环计数器有关。它从 1 开始,跳过第一个数组元素,然后继续达到数组索引处不存在元素的长度。您可以使用 for-of 循环或 forEach
回调来完全避免循环计数器。
我还注意到您在数组 (iput
) 上使用了 +=
运算符。要将元素追加到数组,请使用 push
方法。如果您想要一个字符串,请将 iput
设置为空字符串 (''
) 并保留 +=
。
最后,您省略了几个分号。由于自动插入分号存在缺陷,只要有可能就使用它们来避免意外行为会更容易。
使用普通的 for 循环:
function saveSign() {
const iput = [];
const checkedBoxes = document.querySelectorAll('input[type="checkbox"]');
for(let i = 0; i < checkedBoxes.length; i++) {
iput.push(checkedBoxes[i].id);
}
console.log(iput);
}
使用 for-of循环:
function saveSign() {
const iput = [];
const checkedBoxes = document.querySelectorAll('input[type="checkbox"]');
for(const checkedBox of checkedBoxes) {
iput.push(checkedBox.id);
}
console.log(iput);
}
使用 forEach
回调:
function saveSign() {
const iput = [];
const checkedBoxes = document.querySelectorAll('input[type="checkbox"]');
checkedBoxes.forEach((checkedBox) => {
iput.push(checkedBox);
});
console.log(iput);
}
关于javascript - 在 javascript 中使用数组的动态循环时出现 for 循环问题 Uncaught TypeError : Cannot read property 'id' of undefined at saveSign,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45737427/