我正在尝试做一个简单的循环:
const parent = this.el.parentElement
console.log(parent.children)
parent.children.forEach(child => {
  console.log(child)
})
但我收到以下错误:
VM384:53 未捕获的类型错误:parent.children.forEach 不是函数
即使parent.children日志:
可能是什么问题呢?
注意:这是一个JSFiddle。
我正在尝试做一个简单的循环:
const parent = this.el.parentElement
console.log(parent.children)
parent.children.forEach(child => {
  console.log(child)
})
但我收到以下错误:
VM384:53 未捕获的类型错误:parent.children.forEach 不是函数
即使parent.children日志:
可能是什么问题呢?
注意:这是一个JSFiddle。
的parent.children是像对象的数组。使用以下解决方案:
const parent = this.el.parentElement;
Array.prototype.forEach.call(parent.children, child => {
  console.log(child)
});
的parent.childrenISNodeList类型,就像对象,因为数组:
length表示节点数的属性{0: NodeObject, 1: NodeObject, length: 2, ...}请参阅本文中的更多详细信息。
parent.children是一个HTMLCollection:它实现了可迭代协议。在 ES2015 环境中,您可以将HTMLCollection与任何接受迭代的构造一起使用。
使用HTMLCollection与传播operatator:
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);
}
parent.children不是数组。它是 HTMLCollection 并且它没有forEach方法。您可以先将其转换为数组。例如在 ES6 中:
Array.from(parent.children).forEach(child => {
    console.log(child)
});
或使用扩展运算符:
[...parent.children].forEach(function (child) {
    console.log(child)
});
一个更天真的版本,至少你确定它可以在所有设备上运行,无需转换和 ES6:
const children = parent.children;
for (var i = 0; i < children.length; i++){
    console.log(children[i]);
}
parent.children将返回一个节点列表列表,技术上是一个html Collection。那是一个类似对象的数组,但不是数组,因此您不能直接调用数组函数。在这种情况下,您可以将Array.from()其转换为真正的数组,
Array.from(parent.children).forEach(child => {
  console.log(child)
})
parent.children是一个HTMLCollection类似数组的对象。首先,您必须将其转换为 realArray才能使用Array.prototype方法。
const parent = this.el.parentElement
console.log(parent.children)
[].slice.call(parent.children).forEach(child => {
  console.log(child)
})