最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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

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 a way to use them in an if statement, to exit the control out of If block or restart the if statement?

Share Improve this question edited Apr 24, 2021 at 13:19 ivardu 1893 silver badges17 bronze badges asked Mar 2, 2020 at 7:35 Sherwin SamuelSherwin Samuel 411 gold badge1 silver badge4 bronze badges 4
  • 8 What actual problem are you trying to solve by doing this? – T.J. Crowder Commented Mar 2, 2020 at 7:36
  • 1 What would that do? – deceze Commented Mar 2, 2020 at 7:37
  • 3 This is an XY problem. Please tell us what the real problem is that you're trying to solve, and we will help you with that instead. Also please read (or refresh) How to Ask, as well as this question checklist. And lastly don't forget how to create a minimal reproducible example to show us. – Some programmer dude Commented Mar 2, 2020 at 7:38
  • Thanks but i found the solution, with the help of callbacks – Sherwin Samuel Commented Mar 2, 2020 at 7:55
Add a ment  | 

2 Answers 2

Reset to default 14

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.

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)

发布评论

评论列表(0)

  1. 暂无评论