简体   繁体   中英

TypeScript break switch/case from nested for loop

Essentially, I am looking for the reverse of this question : if I have a for loop nested inside of a switch/case statement, is there a way to break out of the case? Trivial example:

switch (prompt('Left or right?')) {
  case 'left':
    for (let i = 0; i < 10; ++i) {
      if (/* some condition */) {
        break case 'left' // this isn't valid
      }
    }
    break
  // ...
}

Thanks

This is what labels were created for. Apply the label to what you want to break out of and break the named block. In this case, the named block is the switch statement:

 direction: switch (prompt('Left or right?')) { case 'left': for (var i = 0; i < 10; ++i) { if (i==3) { break direction } } console.log('should not get here (remove "direction" above to test)') break default: break } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM