for(var i = 0; i< a.length; i ++){与for(var i in a){ [英] for (var i = 0; i < a.length; i++){ vs. for (var i in a){

查看:198
本文介绍了for(var i = 0; i< a.length; i ++){与for(var i in a){的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
for(var i in aArray)VS for(i = 0; i< aArray.length; i ++)

Possible Duplicate:
for(var i in aArray) VS for(i=0; i<aArray.length; i++)

可以安全地假设它们总是会做同样的事情,而我应该始终使用后者吗?

Is it safe to assume that these will always do the same thing, and that I should always use the latter?

for (var i = 0; i < a.length; i++){

for (var i in a){

推荐答案

不,这并不安全,因为它们不一样.

No it isn't safe, because they're not the same thing.

第一个迭代数字索引,直到按数字顺序将任何值存储在.length属性中.

The first iterates numeric indices up until whatever value is stored in the .length property in numeric order.

第二个枚举对象上的所有可枚举属性,包括原型属性,并且不保证任何顺序.

The second enumerates all enumerable properties on an object, including prototyped properties, and doesn't guarantee any sort of order.

获取数组:

var arr = ['a','b','c'];

现在在其构造函数的prototype对象中添加一些内容:

Now add something to the prototype object of its constructor function:

Array.prototype.sayHello = function() { alert('hi'); };

如果使用for-in语句,最终将击中sayHello函数,而不仅仅是数字索引.

If you use a for-in statement, you'll end up hitting the sayHello function instead of just the numeric indices.

如果您要处理的是除索引之外没有其他属性的对象,并且您不关心顺序,那么我猜这真的没关系,但是正确的形式仍然可以使用for语句.

If you're dealing with objects that don't have enumerable properties aside from the indices, and you don't care about the order, then it really won't matter I guess, but the proper form is still to use a for statement.

这篇关于for(var i = 0; i&lt; a.length; i ++){与for(var i in a){的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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