Leaving a while loop and jumping in one move

There is a similar question in C ++ , but I am using JavaScript here. I am basically in the same situation as the OP in another post.

var input = prompt();
while(true) {
    switch(input) {
        case 'hi':
        break;
        case 'bye':
            //I want to break out of the switch and the loop here
        break;
    }
    /*Other code*/
}

      

Is there a way to do this?

I also have a few radio buttons in the section /*Other code*/

where the code should be split as well.

+3


source to share


4 answers


Wrap the whole thing in a function, then you can just return

break out of both.



var input = prompt();
(function () {
    while(true) {
        switch(input) {
            case 'hi':
            break;
            case 'bye':
            return;
        }
        /*Other code*/
    }
})();

      

+3


source


You can use labels with break statement in js



var input = prompt();

outside:
while(true) {
    switch(input) {
        case 'hi':
        break;
        case 'bye':
            //I want to break out of the switch and the loop here
        break outside;
    }
    /*Other code*/
}

      

+4


source


Don't diminish readability in the name of "fewer lines of code". Make your intentions clear:

while (true) {
  var quit = false;

  switch(input) {
    case 'hi':
      break;

    case 'bye':
      quit = true;
      break;
  }

  if (quit)
    break;

  /*Other code*/
}

      

0


source


This is the same answer found in C ++ or most other languages. Basically, you just add a flag to tell your loop what it has done.

var input = prompt();
var keepGoing = true;
while(keepGoing) {
    switch(input) {
        case 'hi':
            break;
        case 'bye':
            //I want to break out of the switch and the loop here
            keepGoing = false;
            break;
    }
    // If you need to skip other code, then use this:
    if (!keepGoing)  break;
    /*Other code*/
}

      

Make sense?

0


source







All Articles