当我将项目添加到 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]);