Array forEach pass “push” as argument

后端 未结 2 490
梦毁少年i
梦毁少年i 2021-01-21 15:54

Faced strange issue in JS. I receive error on this:

let a = []
let b = [1,2,3]
b.forEach(a.push)
TypeError: Array.prototype.push called on null or undefined
             


        
相关标签:
2条回答
  • 2021-01-21 16:37

    Basically as per the standard syntax of forEach, it is having 3 different parameters, current item, index and the array over which the forEach is called. So push function which was bound with a will be called every time with those parameters. That is the issue here.

    iteration 1 : a.push(1,0,[1,2,3]) //since a was bound with push
    iteration 2 : a.push(2,1,[1,2,3])
    iteration 3 : a.push(3,2,[1,2,3])
    

    Your code will be executed like above.

    0 讨论(0)
  • 2021-01-21 16:51

    Because .forEach() supplies to your callback 3 arguments.

    callback is invoked with three arguments:

    1. the element value
    2. the element index
    3. the array being traversed

    The .push() can accept any number of arguments. So, on each iteration, .push() adds those three arguments to your array.

    0 讨论(0)
提交回复
热议问题