forEach循環(huán)中可使用
return false
終止本次循環(huán)火诸,但不能想for那樣使用break
來跳出整個(gè)循環(huán)。
(1) 終止本次循環(huán)
var array = ["liy","yang","cong","ming"];
array.forEach(function(item,index){
if (item == "cong") {
return false;
}
console.log(item);
});
遍歷數(shù)組所有元素,執(zhí)行到第3次時(shí)媳纬,return false后下面的代碼不再執(zhí)行而已球匕,但還會(huì)繼續(xù)執(zhí)行第4次循環(huán)纹磺。
(2) 跳出整個(gè)循環(huán)
- 錯(cuò)誤用法
var array = ["liy","yang","cong","ming"];
array.forEach(function(item,index){
if (item == "cong") {
break;
}
console.log(item);
});
forEach中不能使用break關(guān)鍵字來跳出整個(gè)循環(huán).png
- 通過拋出異常的方式跳出整個(gè)循環(huán)
try {
var array = ["liy","yang","cong","ming"];
// 執(zhí)行到第3次,結(jié)束循環(huán)
array.forEach(function(item,index){
if (item == "cong") {
throw new Error("EndIterative");
}
alert(item);
});
} catch(e) {
if(e.message!="EndIterative") throw e;
};
// 下面的代碼不影響繼續(xù)執(zhí)行
console.log("haha");
拓展
:JS中的 map, some, every, forEach 用法總結(jié)亮曹,跳出循環(huán) return false break不起作用橄杨。