forEach不是JavaScript数组的函数错误 [英] forEach is not a function error with JavaScript array
本文介绍了forEach不是JavaScript数组的函数错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试制作一个简单的循环:
I'm trying to make a simple loop:
const parent = this.el.parentElement
console.log(parent.children)
parent.children.forEach(child => {
console.log(child)
})
但是我收到以下错误:
VM384:53 Uncaught TypeError:parent.children.forEach不是函数
VM384:53 Uncaught TypeError: parent.children.forEach is not a function
即使 parent.children
日志:
可能是什么问题?
注意:这是一个 JSFiddle 。
推荐答案
parent.children
是一个类似于Array的对象。使用以下解决方案:
The parent.children
is an Array like object. Use the following solution:
const parent = this.el.parentElement;
console.log(parent.children);
Array.prototype.forEach.call(parent.children, child => {
console.log(child)
});
parent.children
是 NodeList
type,这是一个类似于Array的对象,因为:
The parent.children
is NodeList
type, which is an Array like object because:
- 它包含
length
property,表示节点数 - 每个节点都是一个带有数字名称的属性值,从0开始:
{ 0:NodeObject,1:NodeObject,length:2,...}
- It contains the
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, ...}
查看更多详细信息这篇文章。
这篇关于forEach不是JavaScript数组的函数错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文