[英]How do you push a specified number of objects to an array?
我對javascript很陌生,但是我正在嘗試使用以下代碼將指定數量的對象推入數組。 當我檢查控制台時,我看到只有一個對象被推到陣列中。 我應該怎么做? 謝謝!
var albums = {};
function collection(numberOfAlbums) {
array = [];
array.push(albums);
return array;
};
console.log(collection(12));
從您的代碼:
array.push(albums);
會在每次(假設您添加了循環)時添加相同的對象 ,而這並不是您想要的。
這將為numberOfAlbums
每次迭代添加一個新的空對象 :
function collection(numberOfAlbums) {
for (var array = [], i = 0; i < numberOfAlbums; i++) {
array.push({});
}
return array;
};
這是使用map
的另一種方式。 從這里開始 Array.apply
技巧。
function collection(numberOfAlbums) {
var arr = Array.apply(null, Array(numberOfAlbums));
return arr.map(function (el) { return {}; });
};
您始終可以通過以下方式增強數組功能:
Array.prototype.pushArray = function(array){
for (var i = 0; i < array.length; i++){
this.push(array[i]);
}
return this;
};
var array = [];
// This is how you should use the new method added to the prototype
array.pushArray(['1','2','3','5']);
console.log(array); // ["1", "2", "3", "5"]
這樣,現在所有數組都有一個名為pushArray的新方法,它使您可以將整個數組推入一行。
// You can implement another method to receive several objects to be added to an array like this
var array2 = [];
Array.prototype.pushObjects = function(){
for (var i = 0; i < arguments.length; i++){
this.push(arguments[i]);
}
return this;
};
// This is how you should use the new method added to the prototype
array2.pushObjects({foo : 'bar'}, {foo2 : 'bar2'}, {foo3 : 'bar3'});
console.log(array2.length);
// Result:
//[[object Object] {
// foo: "bar"
//}, [object Object] {
// foo2: "bar2"
//}, [object Object] {
// foo3: "bar3"
//}]
希望能幫助到你。
我可以給您代碼,但這不是學習的方法。 所以這是步驟:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.