forEach 不是 JavaScript 数组的函数错误 [英] forEach is not a function error with JavaScript array
问题描述
我正在尝试做一个简单的循环:
I'm trying to make a simple loop:
const parent = this.el.parentElement
console.log(parent.children)
parent.children.forEach(child => {
console.log(child)
})
但我收到以下错误:
VM384:53 未捕获的类型错误:parent.children.forEach 不是函数
VM384:53 Uncaught TypeError: parent.children.forEach is not a function
即使 parent.children
记录:
可能是什么问题?
注意:这是一个 JSFiddle.
推荐答案
第一个选项:间接调用 forEach
parent.children
是一个类似数组的对象.使用以下解决方案:
First option: invoke forEach indirectly
The parent.children
is an Array like object. Use the following solution:
const parent = this.el.parentElement;
Array.prototype.forEach.call(parent.children, child => {
console.log(child)
});
parent.children
是 NodeList
类型,它是一个类似数组的对象,因为:
The parent.children
is NodeList
type, which is an Array like object because:
- 包含
length
属性,表示节点数 - 每个节点都是一个带有数字名称的属性值,从0开始:
{0: NodeObject, 1: NodeObject, length: 2, ...}
- It contains the
length
property, which indicates the number of nodes - Each node is a property value with numeric name, starting from 0:
{0: NodeObject, 1: NodeObject, length: 2, ...}
parent.children
是一个 HTMLCollection
:它实现了 可迭代协议.在 ES2015 环境中,您可以将 HTMLCollection
与任何接受迭代的结构一起使用.
parent.children
is an HTMLCollection
: which implements the iterable protocol. In an ES2015 environment, you can use the HTMLCollection
with any construction that accepts iterables.
将 HTMLCollection
与扩展运算符一起使用:
Use HTMLCollection
with the spread operatator:
const parent = this.el.parentElement;
[...parent.children].forEach(child => {
console.log(child);
});
或者使用 for..of
循环(这是我的首选选项):
Or with the for..of
cycle (which is my preferred option):
const parent = this.el.parentElement;
for (const child of parent.children) {
console.log(child);
}
这篇关于forEach 不是 JavaScript 数组的函数错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!