try catch

两层循环 怎么终止整个循环

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

  1. 捕获异常 只能获取同步 无法捕获异步
  2. 同步 第一行没执行完 不会执行第二行
  3. 容许错误 并且报错 后面的代码继续执行
  4. 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
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值