在的JavaScript回路循环和区别 [英] difference between for loop and for-in loop in javascript

查看:150
本文介绍了在的JavaScript回路循环和区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现有在的JavaScript循环for循环和之间的差异。

I found that there is a difference between for loop and for-in loop in javascript.

当我定义一个新的数组:

When I define a new array:

var a=new Array();

然后我把一些价值成,但不连续,例如:

Then I put some value into in but not contiguously for example:

a[0]=0;a[1]=1;a[4]=4; 

当我使用为(i = 0; I< 5;我++)来获得的价值和使用alert表现出来,这是不同的使用的(在我)

When I use for(i=0;i<5;i++) to get the value and use alert to show it, it's different from using for(i in a).

在previous人会表现出指数2,3元素,显示未定义,而换将只显示指数0,1和4。谁能告诉我为什么?

The previous one will show elements in index 2,3 which shows "undefined" while for-in will show only index 0,1,and 4. Can anybody tell me why?

推荐答案

为(... ...中)通常用于通过对象的属性来迭代(这是什么JavaScript使用关联数组),而典型的循环用于顺序数组。

for (... in ...) is typically used to iterate through the properties of objects (which are what javaScript uses for associative arrays), while the typical for loop is used for sequential arrays.

在你的榜样,你真的创建一个与键的关联数组0,1和4。如果你想要一个真正的JavaScript数组,你会使用 a.push(0) a.push(1)等......为了增加值,顺序中,到年底该数组。

In your example, you are really creating an associative array with the keys 0, 1, and 4. If you wanted a true javaScript array, you'd use a.push(0), a.push(1), etc... in order to add the values, sequentially, onto the end of the array.

使用顺序排列,语法为(VAR I = 0; I&LT; arr.length;我++),使 I 数从0到1小于数组的长度。这将允许 I 等于阵列中的每个索引,一个接一个,让你访问的每个元素的数组中的

With a sequential array, the syntax for (var i = 0; i < arr.length; i++) makes i count from 0 to 1 less than the length of the array. This will allow i to be equal to each index in the array, one-by-one, allowing you to access each element in that array.

使用关联数组,然而,键是不连续的,所以使一个变量计数从0到1小于所述阵列的长度将不会产生所期望的结果。在您的例子是接近的工作,因为你手动创建的键恰好是0,1和4,这几乎是连续的。

With associative arrays, however, the keys are non-sequential, so making a variable count 'from 0 to 1 less than the length of the array' won't produce the desired results. In your example it is close to working because your manually created keys just happen to be 0, 1, and 4, which are almost sequential.

如果您想与非连续按键阵列 - 非连续为0,1,4,等你..--应当使用对象,而不是数组,例如

If you want to have an array with non-sequential keys--'non-contiguous' as in 0, 1, 4, etc..--you should probably use objects, not arrays, e.g.

var obj = {};
obj[0] = 0;
obj[1] = 1;
obj[4] = 4;

,然后用为(... ...中)循环将是正确的语法。

这篇关于在的JavaScript回路循环和区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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