我试着做一个简单的循环:
const parent = this.el.parentElement
console.log(parent.children)
parent.children.forEach(child => {
console.log(child)
})
但我得到以下错误:
Uncaught TypeError: parent.children.forEach不是一个函数
即使父母。孩子的日志:
有什么问题吗?
注:这是一个JSFiddle。
我试着做一个简单的循环:
const parent = this.el.parentElement
console.log(parent.children)
parent.children.forEach(child => {
console.log(child)
})
但我得到以下错误:
Uncaught TypeError: parent.children.forEach不是一个函数
即使父母。孩子的日志:
有什么问题吗?
注:这是一个JSFiddle。
当前回答
你可以检查你是否输入正确的forEach,如果你像在其他编程语言中那样输入forEach,它将不起作用。
其他回答
那是因为父母。children是一个NodeList,并且它不支持.forEach方法(因为NodeList是一个类似数组的结构,但不是数组),因此尝试先通过using将其转换为数组来调用它
var children = [].slice.call(parent.children);
children.forEach(yourFunc);
对于对象,试试这个:
Object.keys(yourObj).forEach(key => {
console.log(key, yourObj[key]);
});
使用JSON.parse ()
str_json = JSON.parse(array);
str_json.forEach(function (item, index) {
console.log(item);
});
你可以检查你是否输入正确的forEach,如果你像在其他编程语言中那样输入forEach,它将不起作用。
一个更简单的版本,至少你确定它可以在所有设备上工作,不需要转换和ES6:
const children = parent.children;
for (var i = 0; i < children.length; i++){
console.log(children[i]);
}
https://jsfiddle.net/swb12kqn/5/