两层循环 怎么终止整个循环
let arr = [
[1, 2, 3, 4, 5],
[99, 66, 3, 1, 999]
]
try {
for (const item of arr) {
for (const itemChild of item) {
if (itemChild === 3) {
throw new Error('终止整个循环')
}
console.log(itemChild) // 1 2
}
}
} catch (e) {
console.log('catch 执行')
console.log(e.message) // 终止整个循环
}
try catch
- 捕获异常 只能获取同步 无法捕获异步
- 同步 第一行没执行完 不会执行第二行
- 容许错误 并且报错 后面的代码继续执行
- throw 输出错误信息 终止程序
只能在 try { 里面使用 },不能在try之外的地方使用throw,包括catch
var arr = [1, 2, 3, 4, 5, 6]
for( var i = 0; i < arr.length; i ++ ) {
if (i === 3) {
break // 终止循环
}
console.log(i) // 0 1 2
}
var array = [1, 2, 3, 4, 5];
for (let index = 0; index < array.length; index++) {
const element = array[index]
if (element === 3) {
continue // 终止本次循环 进入下一次循环
}
console.log(element) // 1 2 4 5
}