简体   繁体   中英

Does a sparse Javascript array with whole number keys remain sorted by key?

For example:

var a = [];
a[5] = 'five';
a[2] = 'two';
a[11] = 'eleven';
a[210] = 'two-ten';
a[4] = 'four';
a[56] = 'fifty-six';
a[1] = 'one';
a[39] = 'thirty-nine';

for( var i in a ) {
    if( a.hasOwnProperty(i) ) {
        console.log(i+":"+a[i]);
    }
}

Results in the following (for a few browsers I have handy to test.)

1:one
2:two
4:four
5:five
11:eleven
39:thirty-nine
56:fifty-six
210:two-ten

Is this standard, reliable behaviour?

They will always be in order, yes, but standards (as far as I'm aware) end up setting all of the in-between indexes as undefined.

Edit: If you initialize it as an object, with curly braces, instead of square braces (for arrays) you may get irregular behaviors between browsers.

ECMA-262 does not specify enumeration order.

Some browser implement them in ordered way others don't, like V8 to save memory.

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