.push()多个对象进入JavaScript数组返回'undefined'

MFr*_*ier 18 javascript arrays

当我向beats数组添加项目然后console.log用户时,我在数组中获得了正确数量的项目.但是当我检查.length时,我总是得到1.尝试调用索引总是会给我'未定义',就像这样: Tom.beats[1] 我想我错过了一些明显的东西,但这是打败了我.我怀疑我滥用这种.push方法,但我不确定.任何帮助是极大的赞赏!(使用Chrome开发工具)

//The USER

function User(name, role){
    this.beats = [ ]; 

    this.name = name;
    this.role = role;

    // add beats to beats array

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

}

// Three New Instances. Three New Users.

var Mal = new User("Mal", "Rapper");
Mal.addBeats(["love", "cash"]);

var Dan = new User("Dan", "Producer");
Dan.addBeats(["cake", "dirt", "sally-mae"]);

var Tom = new User("Tom", "Producer");
Tom.addBeats(["Fun", "Little", "Samsung", "Turtle", "PC"]);

// Check for position in beats array

console.log(Tom.beats); 
console.log(Mal.beats); 
console.log(Dan.beats); 

console.log(Mal.beats[1]);
console.log(Dan.beats[1]);
console.log(Tom.beats[1]);
Run Code Online (Sandbox Code Playgroud)

kay*_*kay 49

Array.push(...)将多个参数附加到列表中.如果你把它们放在一个数组中,那么这个"beats"数组就会被追加.

Array.concat(...) 很可能不是你想要的,因为它生成一个新的数组而不是附加到现有的数组.

您可以使用[].push.apply(Array, arg_list)附加参数列表的项目:

this.addBeats = function(beats) { 
    return [].push.apply(this.beats, beats);
};
Run Code Online (Sandbox Code Playgroud)

  • 每次调用函数时,`[].push`都会创建一个新数组.我想使用`return this.beats.push.apply(this.beats,beats)`会更便宜. (4认同)
  • @AlexanderKachkaev,实际上,不是:http://jsperf.com/nil-push/2.使用`[] .someFunction.call`,`{} .someFunction.apply`等是至少Firefox和Chrome理解和优化的模式.使用`[] .push`,而不是`variable.push`或`Array.prototype.push`要快一些,因为它不会涉及查找变量名. (2认同)
  • 注意:一年后,我的说法不再正确。在Firefox v44和Chrome v46中,“ Array.prototype.push.apply”的速度提高了10%左右。 (2认同)

Ash*_*man 8

传播运营商

在支持传播运算符的环境中,您现在可以执行以下操作:

this.addBeats = function (beats) {
    return this.beats.push(...beats);
};
Run Code Online (Sandbox Code Playgroud)

或者如果你需要更多的控制来覆盖等

this.addBeats = function(beats) { 
    return this.beats.splice(this.beats.length, null, ...beats);
};
Run Code Online (Sandbox Code Playgroud)