当我向节拍数组添加项目,然后对用户执行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]);
发布于 2012-06-18 07:48:24
Array.push(...)
需要多个参数来追加到列表中。如果你把它们放在一个数组中,这个“节拍”数组就会被追加。
Array.concat(...)
很可能不是您想要的,因为它会生成一个新的数组,而不是附加到现有的数组中。
您可以使用[].push.apply(Array, arg_list)
来追加参数列表中的项:
this.addBeats = function(beats) {
return [].push.apply(this.beats, beats);
};
发布于 2016-05-19 18:28:23
扩展运算符
在支持spread operator的环境中,您现在可以执行以下操作:
this.addBeats = function (beats) {
return this.beats.push(...beats);
};
或者如果你需要更多的控制来覆盖等
this.addBeats = function(beats) {
return this.beats.splice(this.beats.length, null, ...beats);
};
发布于 2012-06-18 07:41:36
addBeats()应该将this.beats与beats参数连接起来。
https://stackoverflow.com/questions/11075651
复制相似问题