.push()将多个对象转换为JavaScript数组返回' undefined'

时间:2012-06-17 23:38:56

标签: javascript arrays

当我向beats数组添加项目然后console.log用户时,我得到了数组中正确数量的项目。但是当我检查.length时,我总是得到1。 试图调用索引总是会给我'undefined',如下所示: 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]);

3 个答案:

答案 0 :(得分:49)

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

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

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

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

答案 1 :(得分:7)

传播运营商

在支持spread operator的环境中,您现在可以执行以下操作:

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

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

this.addBeats = function(beats) { 
    return this.beats.splice(this.beats.length, null, ...beats);
};

答案 2 :(得分:1)

addBeats()应该使用beats参数连接this.beats。

相关问题