我正在尝试制作一个简单的循环:
const parent = this.el.parentElement
console.log(parent.children)
parent.children.forEach(child => {
console.log(child)
})
但是我得到以下错误:
VM384:53 Uncaught TypeError: parent.children.forEach is not a function
即使 parent.children
日志:
可能是什么问题?
注意:这是一个JSFiddle .
最佳答案
第一个选项:间接调用 forEach
parent.children
是一个类似数组的对象。使用以下解决方案:
const parent = this.el.parentElement;
Array.prototype.forEach.call(parent.children, child => {
console.log(child)
});
parent.children
是NodeList
类型,它是一个类数组对象,因为:
- 它包含
length
属性,表示节点数 - 每个节点都是一个带有数字名称的属性值,从0开始:
{0: NodeObject, 1: NodeObject, length: 2, ...}
在 this article 中查看更多详细信息.
第二种选择:使用可迭代协议(protocol)
parent.children
是一个 HTMLCollection
:它实现了 iterable protocol .在 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);
}
关于javascript - forEach 不是 JavaScript 数组的函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35969974/