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

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

但我得到以下错误:

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

即使父母。孩子的日志:

有什么问题吗?

注:这是一个JSFiddle。


当前回答

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

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

或者使用展开运算符:

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

其他回答

因为你正在使用ES6的特性(箭头函数),你也可以简单地使用这样的for循环:

(让孩子({0:[{“a”:1、“b”:2},{' c ': 3}]}, {1: []})) { console.log(孩子) }

对于对象,试试这个:

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

不需要forEach,你可以只使用from的第二个参数进行迭代,如下所示:

让节点列表=[{0:[{“a”:1、“b”:2},{' c ': 3}]}, {1: []}] Array.from(nodeList, child => { console.log(孩子) });

你可以检查你是否输入正确的forEach,如果你像在其他编程语言中那样输入forEach,它将不起作用。

使用JSON.parse ()

str_json = JSON.parse(array);
str_json.forEach(function (item, index) {
    console.log(item);
});