这是我尝试运行的方法:
function SayHello() {
    cars = new Array();
    cars[0] = "Toyota";
    cars[1] = "Mitsubishi";
    cars[2] = "Honda";
    for (car in cars) {
        alert(car);
    }
}返回的内容如下:
0
1
2当我将代码更改为以下代码时:
function SayHello() {
    cars = new Array();
    cars[0] = "Toyota";
    cars[1] = "Mitsubishi";
    cars[2] = "Honda";
    for (car in cars) {
        alert(cars[car]);
    }
}它正确地返回了名称。
我的问题是,for-in循环只是以有序的方式返回索引吗?谢谢。
发布于 2010-12-27 00:14:04
是的,它将是集合中的索引。
请参阅here
var mycars = ["Saab", "Volvo", "BMW"];
for (var car in mycars)
{
  document.write(mycars[car] + "<br />");
}正如您所看到的,使用变量作为集合的索引。
您可以使用for each ... in语法(在Javascript1.6中引入)来迭代值。参见here。
for each...in-类似于for...in,但遍历对象的属性值,而不是属性名称本身。( JavaScript 1.6中的新功能。)
据我所知,Javascript 1.6+目前只在火狐中使用。
发布于 2010-12-27 00:20:34
是的,迭代器的值是属性的名称。然而,使用它在数组上循环是非常不受欢迎的。例如,考虑以下内容:
x = ['a', 'b', 'c'];
x.foo = 'bar';
for (i in x) alert(i);  // 0, 1, 2, foo它用于遍历对象的成员:
x = { a : 'apple', b : 'banana', c : 'carrot' };
for (i in x) {
    // and it's best to check that the property actually exists
    // on this object, not just on one of its prototypal ancestors:
    if (x.hasOwnProperty(i)) {
        alert(i);  // 'a', 'b', 'c'
    }
}有关使用YUI Blog的原因的更多信息
发布于 2010-12-27 00:14:37
是也不是。它返回索引,而不是值,并将它们作为带引号的字符串返回。"0“、"1”等。
这样做的好处是,如果您使用javascript对象作为关联数组,for in的工作方式是相同的。
https://stackoverflow.com/questions/4534488
复制相似问题