基于我比较喜欢使用显式非for方式的循环,于是有了以下和forEach循环方法的爱恨情愁......
进入正题:
跳出循环
return
let arr = [1,2,3,4,5,6]
arr.forEach((item) => {
if (item === 3) {
return
}
console.log(item)
})
终止循环
抛出错误
let arr = [1,2,3,4,5,6]
try{
arr.forEach((item) => {
if (item === 3) {
throw new Error('Loop End')
}
console.log(item)
})
} catch (e) {
//if(e.message === 'Loop End') throw e
//终止后要做的操作
}
问题就是得记录,不论大小!
是吧?