简体   繁体   English

数组中的javascript for-in循环

[英]javascript for-in loop in an Array

If the code is this: 如果代码是这样的:

arr=Array("a","b","c");
for(i in arr);
{
 alert(i);
}

there is no any alert,but if it is this: 没有任何警报,但是如果是这样:

arr=new Array("a","b","c");
for(i in arr)
{
 alert(i);//alerts 0,1,2
}

What is the reason? 是什么原因?

Array is a constructor. Array是一个构造函数。 To create a new object you should be using the new operator to create the object, which the constructor is then bound to and run against. 要创建一个新对象,您应该使用new运算符创建该对象,然后将该构造函数绑定到该对象并对其运行。 In this case though, it actually should work either way, your issue is most likely related to the semicolons next to your for-loop, as noted in the comments. 但是,在这种情况下,它实际上应该以任何一种方式起作用,如注释中所述,您的问题很可能与for循环旁的分号有关。

As an aside, for creating a new array its generally advised to use the simpler notation 顺便说一句,为创建新数组,通常建议使用更简单的表示法

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

Its also questionable to use a for-in loop with an array in javascript, as that will hit any additional properties defined on the array. 将for-in循环与javascript中的数组一起使用也是可疑的,因为这会影响数组上定义的任何其他属性。 (so if you said arr.x = 2 it would also iterate over x . (因此,如果您说arr.x = 2它也会在x进行迭代。

Better to use the iterative form 最好使用迭代形式

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

    alert(arr[i]);
}

The reason you're getting different results is that you were using incorrect syntax for your for/in loops. 得到不同结果的原因是for / in循环使用了错误的语法。

for(i in arr);
{
 alert(i);
}

should not have the first semicolon. 不应该有第一个分号。

Also note that a nicer way to iterate over an array would be: 还请注意,迭代数组的更好方法是:

arr.forEach(function(value, index){
    alert(value); // or alert(index);
});

As bfavaretto has mentioned. 正如bfavaretto所提到的。

Invoking the Array function without the new keyword will Create and return a new Array object in the same way it would had you used the new keyword. 不使用new关键字调用Array函数将以与使用new关键字相同的方式创建并返回一个新的Array对象。

So these two will alert the same things: 因此,这两个将提醒相同的事情:

arr1 = new Array("a","b","c");
arr2 = Array("a","b","c");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM