Thoughts from the office by Ed Ball
Tuesday, March 15, 2005

The nicest way to enumerate an array would be to use the for...in operator:

for (var obj in array)
  ...

Don’t do it. The biggest surprise to the uninitiated is that this enumerates the indexes into the array, not the elements of the array itself. You’ll also find that the enumerated indexes are strings rather than integers. Worst of all, you’ll find that the indexes aren’t enumerated in numerical order, but in arbitrary order. You’ve probably figured out by now that what you’re actually doing is enumerating the properties of the array object, which happen to include the properties whose names are non-negative integers, but would also include any other custom properties you had assigned to the array.

So, how to enumerate an array? Well, the best approach is the most obvious – walk through the indexes of the array with a simple for loop:

for (var n = 0; n < array.length; n++)
  DoSomething(array[n]);

For a small speed increase, pull the length out of the loop.

var len = array.length;
for (var n = 0; n < len; n++)
  DoSomething(array[n]);

However, my favorite way to enumerate an array is to call a ForEach function that does all this for me – more on that in a future post...

3/15/2005 10:05:23 AM (Pacific Daylight Time, UTC-07:00) | Comments [0] | Code | JavaScript#
Name
E-mail
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):

Search
Archive
Links
Categories
Administration
Blogroll