这是我尝试运行的方法:
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 循环是否只是以有序的方式返回一个索引?谢谢。
最佳答案
是的,迭代器的值是属性的名称。然而,使用它来遍历数组是非常不受欢迎的。例如,考虑一下:
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
关于javascript - Javascript 'for-in' 函数是否只返回一个索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4534488/