Declaring array of objects

Prasath K picture Prasath K · Apr 1, 2013 · Viewed 401k times · Source

I have a variable which is an array and I want every element of the array to act as an object by default. To achieve this, I can do something like this in my code.

var sample = new Array();
sample[0] = new Object();
sample[1] = new Object();

This works fine, but I don't want to mention any index number. I want all elements of my array to be an object. How do I declare or initialize it?

var sample = new Array();
sample[] = new Object();

I tried the above code but it doesn't work. How do I initialize an array of objects without using an index number?

Answer

Daniel Imms picture Daniel Imms · Apr 1, 2013

Use array.push() to add an item to the end of the array.

var sample = new Array();
sample.push(new Object());

To do this n times use a for loop.

var n = 100;
var sample = new Array();
for (var i = 0; i < n; i++)
    sample.push(new Object());

Note that you can also substitute new Array() with [] and new Object() with {} so it becomes:

var n = 100;
var sample = [];
for (var i = 0; i < n; i++)
    sample.push({});