JavaScript错误“Uncaught TypeError: undefined is not iterable ()”的解决方法

javascript中发生错误“Uncaught TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))”时的原因和解决方法。

JavaScript错误“Uncaught TypeError: undefined is not iterable ()”的解决方法  第1张

错误内容

在尝试获取以下“form”元素时发生什么。

<form id="frm">
  <input type="text" id="aaa" name="zhangsan" />
  <input type="number" id="bbb" name="lisi" />
</form>

</div>

<script>

const form = document.getElementById('frm')

Array.from(form.element).forEach(v => {
  console.log(v);
});

</script>

错误信息

Uncaught TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))
    at Function.from (<anonymous>)

JavaScript错误“Uncaught TypeError: undefined is not iterable ()”的解决方法  第2张

原因

“HTMLFormControlsCollection”获取元素应该使用“elements”而不是“element”。

解決方法

使用“elements”

<form id="frm">
  <input type="text" id="aaa" name="zhangsan" />
  <input type="number" id="bbb" name="lisi" />
</form>

</div>

<script>

const form = document.getElementById('frm')

Array.from(form.elements).forEach(v => {
  console.log(v);
});

</script>

执行结果

JavaScript错误“Uncaught TypeError: undefined is not iterable ()”的解决方法  第3张

本文来源:词雅网

本文地址:https://www.ciyawang.com/javascript-typeerror-2.html

本文使用「 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 」许可协议授权,转载或使用请署名并注明出处。

相关推荐