1 . for in 循环 返回可枚举的属性
语句: for(var obj in objs){ ... }
来用for in遍历一个对象
var objs = {a: 1, b: 2};
for (var obj in objs) {
console.log("key:" + obj + ", value:" + objs[obj]);
} //key:a, value:1 ; key:b, value:2
来用for in遍历一个数组
var arrs = ['nick','lane','mike','james'];
for(var arr in arrs){
console.log('index:'+ arr + ', value:' + arrs[arr]);
}
//index:0, value:nick
//index:1, value:lane
//index:2, value:mike
//index:3, value:james
看上去是不是for in既可以遍历对象也可以遍历数组 , 这里来一个转折
比较 : for循环遍历数组 和for in 循环遍历 数组的区别
// 一个普通的数组
var arrs =[13,5,22,46];
// 在数组原型上扩展一个方法
Array.prototype.extend = function(){
console.log("在数组原型扩展一个方法");
}
// 普通的for 循环遍历
for(var i = 0 ; i < arrs.length; i++){
console.log(i,"类型:"+typeof i,arrs[i]);
}
// 用for in 遍历数组
for(var k in arrs){
console.log(k,"类型:"+typeof k,arrs[k]);
}
输出结果:
//普通的for 循环遍历
0 "类型:number" 13
1 "类型:number" 5
2 "类型:number" 22
3 "类型:number" 46
//用for in 遍历数组
0 类型:string 13
1 类型:string 5
2 类型:string 22
3 类型:string 46
extend 类型:string (){
console.log("在数组原型扩展一个方法");
}
上面for in遍历输出的结果中,多出了一行,这一行就是我们扩展的一个函数
那么问题来了----->如果我们在项目采用的是用for in遍历数组,假设有一天谁不小心自己为了扩展js原生的Array类,或者引入一个外部的js框架也扩展了原生Array , 那我们遍历出来的东西还是我们想要的吗?
综上所诉 for in遍历慎用于遍历数组
2 . forEach循环 不能跳过或者终止循环
语句: arr.forEach(function(v,i,a){ ... });
forEach()函数一般只能用于数组,功能是从头到尾把数组遍历一遍。有三个参数分别是:数组元素,元素的索引,数组本身
var arr = ["aa","bb","cc"]
arr.forEach(function(value){
// if (value ==='cc') {
// break;
// } // 终止循环 如果终止循环会报错
console.log(value)
}) // aa bb cc
但是在ES6新特性中forEach可以用下面的写法来遍历类数组:
let divs = document.querySelectorAll('div'); // 这里是NodeList类数组对象,它里面没有.forEach方法
Array.prototype.forEach.call(divs, function(value,index) {
console.log(index+ ':' + value);
});
3 . for of 循环 es6用法 可终止循环
语句: for(let obj of objs){ ... }
for-of循环用来遍历数据
for-of循环不仅支持数组,还支持大多数类数组对象,例如 NodeList
for-of循环也支持字符串遍历,它将字符串视为一系列的Unicode字符来进行遍历:
//遍历数组
let arrs = ['nick','lane','mike','haha'];
for(let item of arrs){
console.log(item);
} // nick lane mike haha
let arr = [
{ name:'nick', age:11 },
{ name:'lane', age:24 },
{ name:'mike', age:33 },
{ name:'haha', age:40 }
];
for(let item of arr){
console.log(item.name,item.age);
} //nick 11 lane 24 mike 33 haha 40
//遍历类数组
let list = document.querySelectorAll('li')
for(let item of list){
console.log(item);
}
// <li>aaaa</li>
// <li>sssss</li>
// <li>ddddd</li>
// <li>ccccc</li>