怎么中断forEach?
forEach一旦执行,只用过return的话,它是只会跳过本次遍历,还是会走完全部,所以想要中断forEach的话,可以通过在其中手动抛出异常的方法去中断forEach
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
try {
arr.forEach(item => {
if (item > 4) {
throw 'error'
}
console.log(1);
})
} catch (e) {
// catch捕获到 throw 抛出的异常
console.log(e);
}