Javascript为什么FOR IN是一个不好的做法? [英] Javascript why FOR IN is a bad practice?

查看:145
本文介绍了Javascript为什么FOR IN是一个不好的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

JavaScript“ For… in”使用数组

人们总是告诉我使用FOR IN是一种不好的做法,拜托,你能告诉我为什么吗?为什么最好和i一起使用?

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?

我总是喜欢使用FOR IN,因为我在使用PHP时也使用了 foreach 很多,它与javascript中的FOR IN非常类似:)

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 :)

推荐答案

不好的做法是不了解差异枚举数组对象迭代之间。否则 for ... in 循环是很好的工具。有很大的内部差异,但我会尝试以实际的方式解释:

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:

语法是: for(字符串在对象中),其中 object Object 的一个实例(当然,它的任何后代)和 string var在每次循环迭代时接收 object 的属性名称。但数组也是一个对象后代!因此,使用它是完全合法的:

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]);

但只是毫无意义。此外,请注意 [] 上方的括号表示法。这是一种成员运算符,不能与数组元素访问混淆。首先需要类型 string 的操作数和第二个 - 数字。让我们打破上面的例子并使用 var array = new Array(3)创建数组。循环工作不再,但 array.length == 3 正确。

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.

结论:使用 for ... in 。使用表示(var number = 0; number< array.length; number ++) with arrays。

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

by方式,JavaScript 对象与PHP的关联数组(哈希表,如果你坚持正确的术语)类似。语法是 var object = {string:value,anotherName:moreStuff} 。这里 for ... in 派上用场!

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!

进一步阅读

这篇关于Javascript为什么FOR IN是一个不好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆