微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

forEach 不是 JavaScript 数组的函数错误

如何解决forEach 不是 JavaScript 数组的函数错误

第一种选择:间接调用 forEach

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

const parent = this.el.parentElement;

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

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

  • 它包含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);
}

解决方法

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

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

但我收到以下错误:

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

即使parent.children日志:

在此处输入图像描述

可能是什么问题呢?

注意:这是一个JSFiddle

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。