forEach is not a function error with JavaScript array

前端 未结 11 534
梦毁少年i
梦毁少年i 2020-11-29 17:11

I\'m trying to make a simple loop:

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


        
相关标签:
11条回答
  • 2020-11-29 18:03

    There is no need for the forEach, you can iterate using only the from's second parameter, like so:

    let nodeList = [{0: [{'a':1,'b':2},{'c':3}]},{1:[]}]
    Array.from(nodeList, child => {
      console.log(child)
    });

    0 讨论(0)
  • 2020-11-29 18:07

    Since you are using features of ES6 (arrow functions), you may also simply use a for loop like this:

    for(let child of [{0: [{'a':1,'b':2},{'c':3}]},{1:[]}]) {
      console.log(child)
    }

    0 讨论(0)
  • 2020-11-29 18:08

    You can check if you typed forEach correctly, if you typed foreach like in other programming languages it won't work.

    0 讨论(0)
  • 2020-11-29 18:11

    That's because parent.children is a NodeList, and it doesn't support the .forEach method (as NodeList is an array like structure but not an array), so try to call it by first converting it to array using

    var children = [].slice.call(parent.children);
    children.forEach(yourFunc);
    
    0 讨论(0)
  • 2020-11-29 18:13

    parent.children is a HTMLCollection which is array-like object. First, you have to convert it to a real Array to use Array.prototype methods.

    const parent = this.el.parentElement
    console.log(parent.children)
    [].slice.call(parent.children).forEach(child => {
      console.log(child)
    })
    
    0 讨论(0)
提交回复
热议问题