forEach跳出循环
foreach不能使用return或者break跳出循环,因为foreach的参数为回调函数,会遍历执行多个回调函数,return会直接跳出执行的当前的回调函数,其他的回调函数会继续执行,而用break会直接报错,最好的办法是抛出异常,捕获到异常终止遍历
1.return
var arr = [1, 2, 3, 4, 5];
arr.forEach((item) => {
if (item === 2) {
return;
}
console.log(item);
});
跳出了值为2的回调,其他回调依然执行
2.break
var arr = [1, 2, 3, 4, 5];
arr.forEach((item) => {
if (item === 2) {
break;
}
console.log(item);
});
3.抛出异常
try {
var arr = [1, 2, 3, 4, 5];
arr.forEach((item) => {
if (item === 2) {
throw Error("终止");
}
console.log(item);
});
} catch (e) {
console.log(e);
}