首页 > 编程语言 >TypeError: forEach is not a function in JavaScript

TypeError: forEach is not a function in JavaScript

时间:2022-12-15 20:13:33浏览次数:57  
标签:function TypeError const log parent JavaScript forEach child children

 以下代码: 

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

 

标签:function,TypeError,const,log,parent,JavaScript,forEach,child,children
From: https://www.cnblogs.com/jopny/p/16985922.html

相关文章

  • 14个非常棒的JavaScript游戏开发框架推荐
    14个非常棒的JavaScript游戏开发框架推荐随着JavaScript结合​​HTML5​​​开发越来越受欢迎,很多浏览器支持的新功能正被用户使用,与此同时,许多新的​​游戏​​​正在使......
  • VUE使用axios数据请求时报错 TypeError Cannot set property 'xxxx' of undefined 的
    正常情况下在data里面都有做了定义data(){list:"haha"}在函数里面进行赋值this.list=response.data.result这时候你运行时会发现,数据可以请求到,但是会报错TypeErr......
  • Javascript-奖品概率算法
    constLUCKY_AIRDROP_PRIZE=[{"id":1,"prop":16.2},{"id":2,"prop":16.2},{"id":3,"prop":16.2},{"id":4,"prop":16.2},......
  • 彻底搞懂JavaScript防抖与节流
    今天为大家带来一篇JS重难点的知识体系,这也是前端高薪必备的重难点知识,而且防抖与节流在各大企业前端面试过程中经常会考到的高频面试题! 为了更好的帮助大家理解防抖......
  • JavaScript学习--Item1 严格模式
    一、概述除了正常运行模式,ECMAscript5添加了第二种运行模式:“严格模式”(strictmode)。顾名思义,这种模式使得Javascript在更严格的条件下运行。设立”严格模式”的目的,主要......
  • JavaScript内存中的一些形状的读书笔记
    原文地址:http://zoo.zhengcaiyun.cn/blog/article/code-shapeundefined和null不同的原因undefined是栈空间中表示未定义含义的一块特殊的固定的内存区域null是堆内存......
  • Javascript学习
    目录js引入的三种方式js基础语法数组遍历的方法es6中的箭头函数js使用的中的注意点js变量声明的三种方式js引入的三种方式<!DOCTYPEhtml><html> <head> <metachars......
  • JavaScript学习--Item29 DOM基础详解
    看完JavaScript高级程序设计,整理了一下里面的DOM这一块的知识点,比较多,比较碎!DOM在整个页面的地位如图:DOM(文档对象模型)是针对HTML和XML文档的一个API(应用程序编程接口)。DOM......
  • JavaScript的数据类型详解
    数据类型JavaScript中有5种简单数据类型(也称为基本数据类型):Undefined、Null、Boolean、Number和String。还有1种复杂数据类型——Object,Object本质上是由一组无序的名值对......
  • 关于JavaScript的九个思维导图
    学习的道路就是要不断的总结归纳,好记性不如烂笔头,so,下面将po出10张javascript相关的思维导图。思维导图小tips:思维导图又叫心智图,是表达发射性思维的有效的图形思维工具......