开发者

Javascript why FOR IN is a bad practice? [duplicate]

开发者 https://www.devze.com 2023-01-26 20:09 出处:网络
This question already has answers here: Closed 10 years ago. Possible Duplicate: JavaScript “For …in” with Arrays
This question already has answers here: Closed 10 years ago.

Possible Duplicate:

JavaScript “For …in” with Arrays

People always tell me that using FOR IN is a bad practice, please could you tell me why? And why is better to use for with i开发者_C百科?

I always liked to use FOR IN because I use PHP too where I use foreach a lot and it's very similar to FOR IN in javascript :)


Bad practice is not to understand the difference between enumerating over an array object and iterating over it. Otherwise for...in loop is excellent tool. There is big internal difference, but i will try to explain in the practical manner:

Syntax is: for (string in object), where object is an instance of Object (and, naturally, any of its descendants) and string var receives property name of object on each loop iteration. But Array is an Object descendant too! So, it is perfectly legal to use:

var array = [0,1,2];
for (var property in array)
  alert(typeof property + '\t' + property + '\n' + typeof array[property] + '\t' + array[property]);

but simply makes no sense at all. Moreover, note the bracket notation above []. This is a form of membership operator and must not be confused with array element access. First requires operand of type string and second - number. Lets break example above and create array with var array = new Array(3) instead. Loop works no longer, yet array.length == 3 correctly.

Conclusion: use for...in for any objects except arrays. Use for (var number = 0; number < array.length; number++) with arrays.

By the way, JavaScript objects are similar with PHP's associative arrays (hashtables, if you insist on the proper term). Syntax is var object = {string:value,anotherName:moreStuff}. Here for...in comes handy!

Further reading

0

精彩评论

暂无评论...
验证码 换一张
取 消