以下代码:
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