简体   繁体   中英

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

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?

In your array, pushing object in any way is right. That's totally ok. like:

var arr = [];
arr.push({}); // ok
aa[1] = {} // also ok

or:

var arr = [{}, {}, {}]; // the way you are doing is also fine

Or, if you want to do it via loop, that is also fine. Like:

var arr = [];
for(var i=0; i<5; i++){
    arr[i] = {};
}

In general, the way to write

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

in a sane manner without lots of copy paste is to use a for loop:

var array = [];
for(var i=0; i<10; i++){
  array[i] = {};
}

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'

I'm pretty sure that an array like var array = []; is an array of Objects. Based on how Javascript works, you never have to worry about null-pointer exceptions, so just define the array and act like you initialized it with the empty objects and see if it works

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM