在for循环中退出循环有3种方式:return(终止)、break(退出整个循环)、continue(退出当次循环)。
forEach()只能识别上面三种退出循环中的return,其它都识别不了,且return在forEach()中相当于continue。
forEach()可以通过try{}catch(){}结合throw抛错的方式退出循环:
try {
[1,2,3,4,5].forEach((item) => {
if (item > 3) throw new Error('退出forEach循环!')
console.log(item)
})
} catch(e) {
console.log(e)
}
// 输出结果
1
2
3
Error: 退出forEach循环!