Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
93
rated 0 times [  97] [ 4]  / answers: 1 / hits: 55775  / 12 Years ago, wed, november 28, 2012, 12:00:00

In JavaScript I can have an array with holes:



a = [];
a[0] = 100;
a[5] = 200;
a[3] = 300;

a.forEach(function(x) {alert(x);});


I could not find information about whether elements would be processed in ascending order or this is not reliable fact.



I checked that for .. in loop traverses array indices in ascending order, while property names of an object are traversed in the same order they were added to object (at least it looks so).



(I.e. it looks like arrays are internally trees of some kind and objects are hashtables.)



I just found that Rhino JavaScript traverses non-existent elements also:
http://ideone.com/7Z3AFh (unlike for..in).


More From » arrays

 Answers
22

The ECMA-262, 5th edition specification and MDN's Array.forEach() page both show the algorithm for .forEach(), and it will definitely iterate over array elements in ascending index order (skipping indices that were never assigned a value).



Of course, some browsers may not implement that algorithm properly, but I'm not aware of any that don't.


[#81760] Monday, November 26, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zariahdiamondz

Total Points: 649
Total Questions: 109
Total Answers: 88

Location: Tajikistan
Member since Thu, Apr 14, 2022
2 Years ago
;