我可以在JAVASCRIPT中使用继续并在if语句中中断而没有任何循环吗? [英] Can i use continue and break in an if statement without any loops in JAVASCRIPT?

查看:72
本文介绍了我可以在JAVASCRIPT中使用继续并在if语句中中断而没有任何循环吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

众所周知,可以在循环内使用breakcontinue:

It's well-known that break and continue can be used inside a loop:

for (let i = 0; i < 5; i++) {
  console.log(i);
  if (i === 3) {
    break;
  }
}

在循环之外,只是在if语句中有没有办法打破或重新启动if语句?

Is there any way to those in just an if statement instead, outside a loop, to break out of or restart the if statement?

推荐答案

对于break(是)和continue(否),答案是不同的.

The answer is different for break (yes) and continue (no).

您可以在if中使用break,是的,如果标记了if.我不会,但是您可以:

You can use break in an if, yes, if you label the if. I wouldn't, but you can:

foo: if (true) {
    console.log("In if before break");
    break foo;
    console.log("In if after break");
}
console.log("After if");

输出


In if before break
After if

这不是特定于if.您可以标记任何语句,对于那些具有某种主体(循环,switchiftrywith,block等)的语句,可以在主体中使用break摆脱它.例如,这是一个突破block语句的示例:

This isn't specific to if. You can label any statement, and for those with some kind of body (loops, switch, if, try, with, block, ...), you can use break within the body to break out of it. For instance, here's an example breaking out of a block statement:

foo: {
    console.log("In block before break");
    break foo;
    console.log("In block after break");
}
console.log("After block");


In block before break
After block

continue

由于if不是迭代语句,因此不能将continueif(甚至没有标记的)一起使用.摘自规范.

continue

You can't use continue with if (not even a labelled one) because if isn't an iteration statement; from the spec.

如果此 ContinueStatement 没有在 IterationStatement 中直接或间接嵌套(但不跨越函数边界),则是语法错误.

It is a Syntax Error if this ContinueStatement is not nested, directly or indirectly (but not crossing function boundaries), within an IterationStatement.

这篇关于我可以在JAVASCRIPT中使用继续并在if语句中中断而没有任何循环吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆