Javascript Symbol.iterator 不是函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37676768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Symbol.iterator is not a function
提问by zloctb
<div id="par">
<span id="a1"></span>
<span id="a2"></span>
<div id="par2">
<span id="a3"></span>
<span id="a4"></span>
</div>
</div>
<script>
var ele = document.querySelectorAll('#par span');
for( var p of ele ){
console.log(p);
}
</script>
When i run this code I see error
当我运行此代码时,我看到错误
Uncaught TypeError: ele[Symbol.iterator] is not a function
未捕获的类型错误:ele[Symbol.iterator] 不是函数
How to fix this problem ?
如何解决这个问题?
回答by Pranav C Balan
Convert NodeList
to Array
for make it in iterable form, use Array.from()
to convert it.
转换NodeList
为Array
for 使其成为可迭代的形式,用于Array.from()
转换它。
<div id="par">
<span id="a1"></span>
<span id="a2"></span>
<div id="par2">
<span id="a3"></span>
<span id="a4"></span>
</div>
</div>
<script>
var ele = document.querySelectorAll('#par span');
for (var p of Array.from(ele)) {
console.log(p);
}
</script>
Refer the following question for more info : Are HTMLCollection and NodeList iterables?
有关更多信息,请参阅以下问题:Are HTMLCollection 和 NodeList 可迭代吗?