我试着做一个简单的循环:

const parent = this.el.parentElement
console.log(parent.children)
parent.children.forEach(child => {
  console.log(child)
})

但我得到以下错误:

Uncaught TypeError: parent.children.forEach不是一个函数

即使父母。孩子的日志:

有什么问题吗?

注:这是一个JSFiddle。


当前回答

对于对象,试试这个:

  Object.keys(yourObj).forEach(key => {
    console.log(key, yourObj[key]);
  });

其他回答

的父母。children是一个HTMLCollection类数组对象。首先,您必须将其转换为一个真正的数组才能使用Array。原型的方法。

const parent = this.el.parentElement
console.log(parent.children)
[].slice.call(parent.children).forEach(child => {
  console.log(child)
})

的父母。Children不是数组。它是HTMLCollection,它没有forEach方法。您可以先将其转换为数组。例如在ES6中:

Array.from(parent.children).forEach(child => {
    console.log(child)
});

或者使用展开运算符:

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

第一个选项:间接调用forEach

父。children是一个类似数组的对象。请使用以下解决方案:

const parent = this.el.parentElement;

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

父。children是NodeList类型,这是一个类似数组的对象,因为:

它包含length属性,该属性表示节点的数量 每个节点都是一个具有数字名称的属性值,从0开始:{0:NodeObject, 1: NodeObject,长度:2,…}

在本文中查看更多细节。


第二个选择:使用可迭代协议

的父母。children是一个HTMLCollection:它实现了可迭代协议。在ES2015环境中,你可以将HTMLCollection与任何接受可迭代对象的结构一起使用。

使用HTMLCollection和扩展操作符:

const parent = this.el.parentElement;

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

或者使用循环的for..(这是我的首选):

const parent = this.el.parentElement;

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

你可以使用childNodes而不是child,考虑到浏览器兼容性问题,childNodes也更可靠,更多信息在这里:

parent.childNodes.forEach(function (child) {
    console.log(child)
});

或者使用展开运算符:

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

的父母。children将返回一个节点列表列表,技术上是一个html集合。这是一个类似于object的数组,但不是数组,所以你不能直接在它上面调用数组函数。在这种情况下,你可以使用array .from()将其转换为一个真正的数组,

Array.from(parent.children).forEach(child => {
  console.log(child)
})