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

前端 未结 3 1382
慢半拍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 04:58

    Spread operator

    In environments that support the spread operator you may now do the following:

    this.addBeats = function (beats) {
        return this.beats.push(...beats);
    };
    

    Or if you need more control for overwriting etc

    this.addBeats = function(beats) { 
        return this.beats.splice(this.beats.length, null, ...beats);
    };
    
    0 讨论(0)
  • 2021-02-07 05:06

    addBeats() should concat this.beats with the beats parameter.

    0 讨论(0)
  • 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);
    };
    
    0 讨论(0)
提交回复
热议问题