TypeError: forEach is not a function in JavaScript

 以下代码: 

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 is NodeList 类型, 类似Array的object:

  • 包含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, ...}

解决方法1:

const parent = this.el.parentElement;

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

解决方法2:

const parent = this.el.parentElement;

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

解决方法3:

const parent = this.el.parentElement;

for (const child of parent.children) {
  console.log(child);
}

 

posted @ 2022-12-15 19:57  jopny  阅读(1284)  评论(0编辑  收藏  举报