簡體   English   中英

如何將指定數量的對象推送到數組?

[英]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"
//}]

希望能幫助到你。

我可以給您代碼,但這不是學習的方法。 所以這是步驟:

  1. 使用numberOfAlbums作為函數中的參數。
  2. 創建一個空數組。
  3. 在該for循環推相冊中的for循環中使用numberOfAlbums。 == array.push(相冊)==請勿在相冊周圍使用{}括號。
  4. 返回數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM