8

Possible Duplicate:
JavaScript “For …in” with Arrays

In which situations using

for (var i = 0; i < array.length; i++)

is different from using

for (var i in array)

in JavaScript?

Community
  • 1
  • 1

1 Answers1

4
for (var i = 0; i < array.length; i++)

is best for traversing an array, visiting all of the array elements in order.

On modern javascript engines, array.forEach is often cleaner.

for (var i in object) // with object.hasOwnProperty

is used to go through the enumerable properties of an OBJECT, including inherited enumerable properties. Order is not assured. Though an array is an object and this method "works" for arrays, it isn't ideal as returned properties may not be in any particular order. In addition, if any monkey patches or shims are put into place on the array object, they can show up here.

RobG
  • 142,382
  • 31
  • 172
  • 209
Jeremy J Starcher
  • 23,369
  • 6
  • 54
  • 74
  • That is why people confuse Javascript properties with associative arrays. They do have a number of points in common, including being able to iterate over them. Now, of course, not all properties can be iterated over. Host objects follow their own rules and `strict mode` gives the option of making some properties `DontEnum`. – Jeremy J Starcher Sep 06 '12 at 03:40