目录
1. for 遍历数组
1.1 for 的普通遍历
var name = ['Peter','Stark','Jack'];
// for 循环
for(var i = 0; i < name.length; i++) {
console.log(name[i]);
}
1.2 for 优化版遍历
var name = ['Peter','Stark','Jack'];
// 先缓存 name.length
for(var i = 0, len = name.length; i < len; i++) {
console.log(name[i]);
}
2.while 遍历数组
// while 循环
var i = 0;
while (i < name.length) {
console.log(name[i]);
i++;
}
//while 逆向遍历
var i = name.length;
while (i--) {
console.log(name[i]);
}
3. for...in 方法
注意:
1.index索引为字符串型数字,不能直接进行几何运算
2.遍历顺序有可能不是按照实际数组的内部顺序
3.使用for in会遍历数组所有的可枚举属性,包括原型。例如上栗的原型方法method和name属性
所以for in更适合遍