1

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?

4
  • I haven't got the details to hand, but I found different behaviours in some browsers when I looked at this a couple of years ago... Commented May 2, 2015 at 19:37
  • @Adam: Really? I haven't. Commented May 2, 2015 at 19:37
  • If you initialize it as an object, with curly brackets, instead of square brackets (for arrays) you may get irregular behaviors between browsers. Commented May 2, 2015 at 19:40
  • Arrays are always in order. always. Commented May 2, 2015 at 20:08

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Correct. If the OP iterated over the array properly (i.e. from 0 to a.length then he'd see that, if only because it's inherent). His loop ATM is a bit hacky.
I know undefined indices are created and I know that for..length would include them. What I don't know is if iterating it sparsely would always be in numeric order. That's the use case I'm interested in.
@pixelmike Yes, it will be, as long as it is in fact an array object and not a regular old object.
0

ECMA-262 does not specify enumeration order.

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

4 Comments

That's initialized as a regular object, not an array.
[] is an array constructor
Correct. There is no array constructor used in the link you specified. An array is, by definition, an indexed (ordered) list.
v8 keeps plain object properties in insertion order, expect for numerical indices, which it orders.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.