问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/12292523/difference-between-a-basic-for-loop-and-a-for-in-loop-in-javascript