Can i use continue and break in an if statement without any loops in JAVASCRIPT?

纵饮孤独 提交于 2020-03-17 03:37:59

问题


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;
  }
}

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


回答1:


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

break

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");

That outputs

In if before break
After if

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

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

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




回答2:


Normally you can't. You can only use return; to discontinue code execution in an if statement.

Using break;

if (true) {
  break;
}
console.log(1)

Using continue;

if (true) {
  continue;
}
console.log(1)


来源:https://stackoverflow.com/questions/60484353/can-i-use-continue-and-break-in-an-if-statement-without-any-loops-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!