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 @   jopny  阅读(1351)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
历史上的今天:
2021-12-15 vscode编译esp-idf项目时编译正常,但部分代码下有下划线,提示未定义标识符的解决办法,代码补全及函数跳转
点击右上角即可分享
微信分享提示