Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring array of objects

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?

like image 439
Prasath K Avatar asked Apr 01 '13 11:04

Prasath K


People also ask

How do you declare an array of objects in class?

Creating an Array of Objects We can use any of the following statements to create an array of objects. Syntax: ClassName obj[]=new ClassName[array_length]; //declare and instantiate an array of objects.

How do you declare an array of objects in C++?

Syntax: ClassName ObjectName[number of objects]; The Array of Objects stores objects. An array of a class type is also known as an array of objects.

How do you declare an array of objects in Node JS?

After creating an Array object, we can insert data. Use [] with index if you want to assign the value. array[0] = 3; array[1] = 5; array[2] = 12; array[3] = 8; array[4] = 7; You can also use the push() function to insert data.


1 Answers

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({}); 
like image 113
Daniel Imms Avatar answered Oct 07 '22 03:10

Daniel Imms