JoJo
JoJo

Reputation: 20115

How are empty cells stored in a sparse array in JavaScript?

I have a situation where I may be setting an array cell of a high index without setting any of the cells before it.

>>> var arr = [];
undefined
>>> arr[5] = 'value';
"filled"
>>> arr
[undefined, undefined, undefined, undefined, undefined, "filled"]

How is such an array stored in memory? Is there space allocated for each undefined value?

In my actual project, I may be using very large indices. For example, I may set cells 500-800 and 900-1000. I can't use a hash because I need to loop through these non-empty cells and be aware of their index. I want to know if fragmenting the array like this will use up a ton of memory for the empty cells.

Upvotes: 4

Views: 322

Answers (3)

vol7ron
vol7ron

Reputation: 42099

Strapping onto aefxx's answer, you can still iterate:

var obj = {500: "foo",  10923: "bar"};
var max = 0;

for (var key in obj)
   max=key>max?key:(max||key);         // get max key

for (var i=0; i<=max; i++)
   console.log(obj[i]);                // output even the undefined

As Phrogz commented, it doesn't allocate for undeclared elements of the array. I'm not certain if that's the case if you explicitly set the element value to undefined (e.g. arr[somenum] = undefined;)

Upvotes: 1

aefxx
aefxx

Reputation: 25249

I can't use a hash because I need to loop through these non-empty cells and be aware of their index.

What's wrong with the for (x in ...) language construct?

EDITED to accomodate vol7ron's comment:

var x = {2: "foo", 999: "bar"};

for ( var n in x ) {
    if ( x.hasOwnProperty(n) ) {
        console.log(n);
        console.log(x[n]);
    }
}  

Upvotes: 1

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382132

You should probably simply store the max index in a variable and the access your map like this :

for (var i=0; i<=maxIndex; i++) {
 console.log(myMap[i]);
}

Then you'll have the (relative) compacity of the map and the ability to loop through unsetted indexes.

Upvotes: 0

Related Questions