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

javascript

Solution

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'

Problem

``` 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?

Original source