.push() multiple objects into JavaScript array returns 'undefined'

前端 未结 3 1381
慢半拍i
慢半拍i 2021-02-07 04:54

When I add items to the beats array and then console.log the User, I\'m getting the correct number of items in the array. But when I check .length, I always get 1. Trying to ca

3条回答
  •  清酒与你
    2021-02-07 05:23

    Array.push(...) takes multiple arguments to append to the list. If you put them in an array itself, this very array of "beats" will be appended.

    Array.concat(...) is most likely not what you are looking for, because it generates a new array instead of appending to the existing one.

    You can use [].push.apply(Array, arg_list) to append the items of the argument list:

    this.addBeats = function(beats) { 
        return [].push.apply(this.beats, beats);
    };
    

提交回复
热议问题