在js的forEach里使用break
2022-08-22 本文已影响0人
Frank_Fang
一个不优雅的跳出forEach循环体方法
(当然也可以使用every 或者 some等)
const arr = [1, 2, 3, 4, 3, 2]
isBreak = false
arr.forEach(item => {
if (!isBreak && item < 3) {
isBreak = true
console.log(item)
}
})
在forEach里合法的使用break
function breakForEach(arr) {
let BreakException = {};
let res = false;
try {
arr.forEach(item => {
console.log(item)
if (item === 3) {
res = true;
throw BreakException;
}
})
} catch (e) {
if (e !== BreakException) {
throw e
}
}
return res;
}
breakForEach([1, 2, 3, 4, 5, 6, 7]); // true