TypeError: can't convert undefined to object — without undefined or object

前端 未结 1 1797
面向向阳花
面向向阳花 2021-01-19 04:16

Consider the code

const arr = [];
[1].map(arr.push)

This gives TypeError: can\'t convert undefined to object (on Firefox at le

相关标签:
1条回答
  • 2021-01-19 04:48

    That's because arr.push is just a reference to a generic function not bound to arr.

    Therefore, when called as a callback, it doesn't know on which array you want to push

    var func = [].push;
    func(123); // TypeError: can't convert undefined to object
    

    This will work, but multiple arguments will be passed to push, which you probably don't want

    const arr = [];
    [1, "a"].map(arr.push.bind(arr)); // [ 3, 6 ]
    arr; /* [  1,  0, [1, "a"],
             "a",  1, [1, "a"]  ] */
    

    So just use your [1].map(v => arr.push(v))

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