.push() 将多个对象放入 JavaScript 数组返回“未定义”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11075651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
.push() multiple objects into JavaScript array returns 'undefined'
提问by MFrazier
When I add items to the beats array and then console.log the User, I'm getting the correct number of items in the array. But when I check .length, I always get 1.
Trying to call the index will always give me 'undefined' like so:
Tom.beats[1]I think I'm missing something obvious, but this is beating me. I suspect that I'm misusing the .pushmethod but I'm unsure. Any help is greatly appreciated!
(using Chrome dev tools)
当我将项目添加到 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]);
回答by kay - SE is evil
Array.push(...)takes multiple arguments to append to the list. If you put them in an array itself, this very array of "beats" will be appended.
Array.push(...)将多个参数附加到列表中。如果你把它们放在一个数组中,这个“节拍”数组将被附加。
Array.concat(...)is most likely not what you are looking for, because it generates a new array instead of appending to the existing one.
Array.concat(...)很可能不是您要查找的内容,因为它会生成一个新数组而不是附加到现有数组。
You can use [].push.apply(Array, arg_list)to append the items of the argument list:
您可以使用[].push.apply(Array, arg_list)附加参数列表的项目:
this.addBeats = function(beats) {
return [].push.apply(this.beats, beats);
};
回答by Ashley Coolman
Spread operator
展开运算符
In environments that support the spread operatoryou may now do the following:
在支持扩展运算符的环境中,您现在可以执行以下操作:
this.addBeats = function (beats) {
return this.beats.push(...beats);
};
Or if you need more control for overwriting etc
或者,如果您需要更多控制覆盖等
this.addBeats = function(beats) {
return this.beats.splice(this.beats.length, null, ...beats);
};
回答by jmulligan
addBeats() should concat this.beats with the beats parameter.
addBeats() 应该将 this.beats 与 beats 参数连接起来。

