Array forEach pass “push” as argument

后端 未结 2 491
梦毁少年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.

提交回复
热议问题