Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
31
rated 0 times [  33] [ 2]  / answers: 1 / hits: 5936  / 11 Years ago, sun, february 2, 2014, 12:00:00
var array = [];

var object = {};


Now, I need an array of empty objects.



array[0] = {};
array[1] = {};
//........
//........


and



var array = [{}];


is obviously not right.



How to define array of (empty) objects in JS?



var array = [{},{},{},{},.........];


Thanks.



EDIT:



The reason I need is the same reason that having an array with undefined length is useful, and mathematically natural in some cases.



I need object wrappers, and for initialization, it's just an empty object, like some values are null or undefined in many cases.



so, I'll have



var object = {};



array[0].value = 'foo', array[1].value = 'bar'.....



However, I do need multiple object wrappers, and the number is not pre-determined, so consequently, I need an arrays of the objects.



So, I am sorry, I modify my Question title



JavaScript How to define an array of undefined length of empty objects?


More From » javascript

 Answers
1

Arrays can grow and shrink dynamically. So from a certain point of view, they are already of undefined length. You can always add new objects to it if you want to.



You can also create a helper function which checks first if an object exists at a certain position and if not, creates a new one.



You mentioned array[2].value = 'foo' as an example. Here is a helper function that you could use:



function getObjectAtIndex(arr, index) {
return arr[index] || (arr[index] = {});
}


and then, instead of writing array[2].value = 'foo', you'd write:



getObjectAtIndex(array, 2).value = 'foo'

[#48146] Friday, January 31, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
megb

Total Points: 230
Total Questions: 113
Total Answers: 100

Location: Tokelau
Member since Sun, May 7, 2023
1 Year ago
;