简体   繁体   中英

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.

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]);
    }
}  

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 (eg arr[somenum] = undefined; )

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.

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