let arr = [{a:1},{a:2},{a:3},{a:4},{a:5}];
1.for
使用示例:
for(let item =0;item<arr.length;item++){
if(item == 3){
break; //终止循环
continue; //跳过本次循环
return; // return所在函数
}
}
2.forEach
使用示例:
arr.forEach((item)=>{
if(item.a==2){
item.a = 8; //数组内变量为引用类型,遍历参数即为对应项的引用地址
return //跳过本次循环,即return本次遍历函数
}
});
forEach本身无法跳出所以循环,可采用将forEach放入try{},catch{},手动抛出异常的方式
3.for of
使用示例:
for(let item of arr){
if(item.a==3){
item.a = 9;数组内变量为引用类型,遍历所得即为对应项的引用地址
return;// return所在函数
break;//终止循环
continue;//跳过本次循环
}
}
4.for in
for(let item in arr){
if(item == 3){
return;// return所在函数
break;//终止循环
continue;//跳过本次循环
}
}
for in主要用于遍历对象属性