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?
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.
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.
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.
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({});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With