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)
在支持传播运算符的环境中,您现在可以执行以下操作:
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)