forEach 不是 JavaScript 数组的函数错误

新手上路,请多包涵

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

const parent = this.el.parentElement
console.log(parent.children)
parent.children.forEach(child => {
  console.log(child)
})

但我收到以下错误:

VM384:53 未捕获的类型错误:parent.children.forEach 不是函数

即使 parent.children 记录:

在此处输入图像描述

可能是什么问题呢?

注意:这是一个 JSFiddle

原文由 alexchenco 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 854
2 个回答

第一种选择:间接调用 forEach

parent.children 是一个类似数组的对象。使用以下解决方案:

 const parent = this.el.parentElement;

 Array.prototype.forEach.call(parent.children, child => {
 console.log(child)
 });

parent.childrenNodeList 类型,它是一个类似数组的对象,因为:

  • 它包含 length 属性,表示节点的数量

  • 每个节点都是一个具有数字名称的属性值,从 0 开始: {0: NodeObject, 1: NodeObject, length: 2, ...}

本文 中查看更多详细信息。


第二种选择:使用可迭代协议

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);
 }

原文由 Dmitri Pavlutin 发布,翻译遵循 CC BY-SA 4.0 许可协议

parent.children 不是数组。它是 HTMLCollection,它没有 forEach 方法。您可以先将其转换为数组。例如在 ES6 中:

 Array.from(parent.children).forEach(child => {
    console.log(child)
});

或使用扩展运算符:

 [...parent.children].forEach(function (child) {
    console.log(child)
});

原文由 madox2 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题