问题描述
第一种选择:间接调用 forEach
是一个类似parent.children
数组的对象。使用以下解决方案:
const parent = this.el.parentElement;
Array.prototype.forEach.call(parent.children, child => {
console.log(child)
});
parent.children
is类型,它是一个类似NodeList
数组的对象,因为:
在本文中查看更多详细信息。
第二种选择:使用可迭代协议
parent.children
是一个HTMLCollection
:
它实现了可迭代协议。在 ES2015
环境中,您可以将HTMLCollection
与接受迭代的任何构造一起使用。
HTMLCollection
与扩展运算符一起使用:
const parent = this.el.parentElement;
[...parent.children].forEach(child => {
console.log(child);
});
或者使用for..of
循环(这是我的首选):
const parent = this.el.parentElement;
for (const child of parent.children) {
console.log(child);
}
解决方法
我正在尝试制作一个简单的循环:
const parent = this.el.parentElement
console.log(parent.children)
parent.children.forEach(child => {
console.log(child)
})
但我收到以下错误:
VM384:53 未捕获的类型错误:parent.children.forEach 不是函数
即使parent.children
日志:
可能是什么问题呢?
注意:这是一个JSFiddle。