JS中break、continue、return跳出循环的用法和区别

一、break

作用: 立刻退出包含在最内层的循环或者退出一个 switch 语句。

使用特点:

  1. switch 判断语句
  2. 循环语句:for、do/while、while、for/in、for/of
  3. 不能在 forEach、map 遍历中使用,否则会报错:Uncaught SyntaxError: Illegal break statement

例:

function fn() {
  let arr = [1,2,3,4,5]
  for (let item of arr) {
    if (item===3) {
      break
    }
    console.log(item)
  }
}

fn()

/* 输出: */
//  1
//  2

二、continue

作用: continue 语句和 break 语句相似,不同的是,continue 不退出循环,只跳过当前循环。

使用特点:

  1. switch 判断语句
  2. 循环语句:for、do/while、while、for/in、for/of
  3. continuedo/whilewhile 循环体中使用,会出现 死循环,引起程序崩溃,一定要慎之又慎

例: 以下循环只跳过了 i === 3 时的这一次迭代。

function fn() {
  for(var i = 0; i < 5; i++) {
    if(i === 3) {
      continue
    }
    console.log(i)
  }
}

fn()

/* 输出: */
//  0
//  1
//  2
//  4

三、return

作用: return 用于返回函数的返回值,因此 return 语句只能出现在函数体内,否则会报错:Uncaught SyntaxError: Illegal return statement

使用特点:

  1. 只能用在 function 函数体内
  2. for、do/while、while、for/in、for/of 中会退出循环,类似 break 的效果
  3. forEach、map 遍历中,只跳过当前循环,会继续下次迭代,类型 continue 的效果

例1:while 中当执行到 i === 3 ,会退出循环。

function fn() {
  let i = 0
  while (i<5) {
    if (i===3) {
      return
    }
    console.log(i)
    i ++
  }
}

fn()

/* 输出: */
//  0
//  1

例2: 在 forEach 循环中只跳过了 i === 2 时的这一次迭代

function fn() {
  let arr = Array(5).fill(1)
  arr.forEach((item, index)=>{
    if (index===2) {
      return
    }
    console.log(index)
  })
}

fn()

/* 输出: */
//  0
//  1
//  3
//  4

转载:JS中break、continue、return跳出循环的用法和区别 - 简书 (jianshu.com)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值