forEach 不是 JavaScript 数组的函数错误 [英] forEach is not a function error with JavaScript array

查看:51
本文介绍了forEach 不是 JavaScript 数组的函数错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做一个简单的循环:

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.childrenNodeList 类型,它是一个类似数组的对象,因为:

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, ...}

this中查看更多详细信息文章.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆