我的 HTML 中有一些元素类 node-item
,我在我的组件中访问它们使用:
let nodeItems = document.getElementsByClassName('node-item');
当我登录 nodeItems
它给了我一个 HTMLCollection[]
长度为 4。
我尝试了很多方法,但仍然无法迭代 nodeItems
:
1-第一次尝试:
let bar = [].slice.call(nodeItems);
for (var g of bar){
console.log(g); //gives me nothing
}
2 秒尝试:
for(let c of <any>nodeItems) {
console.log(c); //gives me nothing
}
我尝试了数组迭代和对象迭代,但仍然 undefined
或 error
。也试过:
let nodeItems = document.querySelector(selectors);
但是同样的问题。
原文由 Fateme Fazli 发布,翻译遵循 CC BY-SA 4.0 许可协议
nodeItems
是HTMLCollection
,它是类数组对象。它在现代浏览器中是可迭代的。迭代器支持
downlevelIteration
启用编译器选项,在这种情况下它将是:Iterables 可以在旧的浏览器中进行 polyfill。
core-js
为 DOM 迭代提供 polyfill 。否则
nodeItems
可以转换为数组并照常迭代: