Difference between a basic for

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?


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.

链接地址: http://www.djcxy.com/p/70024.html

上一篇: 枚举knockout中的observableArray将其转换为字符串?

下一篇: 一个基本的区别