Difference between a basic for-loop and a for-in-loop in JavaScript [duplicate]

六眼飞鱼酱① 提交于 2019-12-01 02:10:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!