这是我试图运行的方法:
function SayHello() {
cars = new Array();
cars[0] = "Toyota";
cars[1] = "Mitsubishi";
cars[2] = "Honda";
for (car in cars) {
alert(car);
}
}
Run Code Online (Sandbox Code Playgroud)
这返回:
0
1
2
Run Code Online (Sandbox Code Playgroud)
当我将代码更改为:
function SayHello() {
cars = new Array();
cars[0] = "Toyota";
cars[1] = "Mitsubishi";
cars[2] = "Honda";
for (car in cars) {
alert(cars[car]);
}
}
Run Code Online (Sandbox Code Playgroud)
它正确地返回了名称.
我的问题是,for-in循环是否只是有序地返回一个索引?谢谢.
是的,迭代器的值是属性的名称.然而,使用它来遍历数组是非常不赞成的.例如,考虑一下:
x = ['a', 'b', 'c'];
x.foo = 'bar';
for (i in x) alert(i); // 0, 1, 2, foo
Run Code Online (Sandbox Code Playgroud)
它旨在迭代对象的成员:
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'
}
}
Run Code Online (Sandbox Code Playgroud)
有关YUI博客上的原因的更多信息
是的,它将是集合中的索引.
看到这里:
var mycars = ["Saab", "Volvo", "BMW"];
for (var car in mycars)
{
document.write(mycars[car] + "<br />");
}
Run Code Online (Sandbox Code Playgroud)
如您所见,使用变量作为集合的索引.
您可以使用将迭代值的for each ... in语法(在Javascript 1.6中引入).看到这里.
for each...in- 类似于for...in,但迭代对象属性的值,而不是属性名称本身.(JavaScript 1.6中的新功能.)
据我所知,Javascript 1.6+目前仅在Firefox中使用.
| 归档时间: |
|
| 查看次数: |
7466 次 |
| 最近记录: |