如何将指定数量的对象推送到数组?

时间:2016-02-19 16:43:39

标签: javascript arrays

我对javascript很新,但我正在尝试使用以下代码将指定数量的对象推送到数组。当我检查控制台时,我看到只有一个对象被推送到数组。我应该做些什么呢?谢谢!

var albums = {};

function collection(numberOfAlbums) {
    array = [];
    array.push(albums);
    return array;

};

console.log(collection(12));

3 个答案:

答案 0 :(得分:0)

从你的代码:

array.push(albums);

每次都会添加相同的对象(假设你添加了一个循环),这不是你想要的。

这将为numberOfAlbums的每次迭代添加一个新的空对象

function collection(numberOfAlbums) {
  for (var array = [], i = 0; i < numberOfAlbums; i++) {
    array.push({});
  }
  return array;
};

这是使用map的另一种方式。 Array.apply技巧from here

function collection(numberOfAlbums) {
  var arr = Array.apply(null, Array(numberOfAlbums));
  return arr.map(function (el) { return {}; });
};

答案 1 :(得分:-1)

您可以随时使用以下内容扩充阵列功能:

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

希望它有所帮助。

答案 2 :(得分:-1)

我可以给你代码,但那不是学习。以下是步骤:

  1. 使用numberOfAlbums作为函数中的参数。
  2. 创建一个空数组。
  3. 在for循环推送专辑中使用for循环中的numberOfAlbums。 == array.push(albums)==不要在专辑周围使用{}花括号。
  4. 返回数组。