在 javascript Uncaught TypeError 中使用数组的动态循环时,for 循环中的问题:无法在 saveSign 读取未定义的属性“id”

苏曼

我在 for 循环中的这段代码中得到以下错误但是当我给 iput+=checkedBoxes[1].id staticaly 意味着它正在工作请帮助并警告 for 循环正在使用 s

错误:未捕获的类型错误:无法在 saveSign 读取未定义的属性“id”

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)
}
kamoroso94

问题与您的 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);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

Related 相关文章

热门标签

归档