javascript - forEach 不是 JavaScript 数组的函数错误

标签 javascript ecmascript-6 vue.js

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

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 日志:

enter image description here

可能是什么问题?

注意:这是一个JSFiddle .

最佳答案

第一个选项:间接调用 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, ...}

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/

相关文章:

javascript - VueJS - 查看模型、子项和更新值

javascript - 为什么符号不隐式转换字符串

javascript - 以不可变的方式过滤2层数组对象

javascript - 奇怪的代码行为

reactjs - 使用 ES6 在 React 组件中定义方法的语法是什么

javascript - 对于函数范围的变量,用 const 代替 var?

javascript - vuedraggable 句柄属性不起作用

javascript - 如何在 VueJs 中动态添加属性

javascript - KO/JS : Refreshing an array by only pushing new values and keeping existing ones

javascript - 查找下一个隐藏的 div 并使用 jQuery 选择器显示它