admin管理员组文章数量:1289527
There is a similar question concerning this problem in C++, but I'm using JavaScript here. I'm basically in the same situation as the OP in the other 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 anyway to do that?
I also have multiple switches in the /*Other code*/
section where the code should also break.
There is a similar question concerning this problem in C++, but I'm using JavaScript here. I'm basically in the same situation as the OP in the other 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 anyway to do that?
I also have multiple switches in the /*Other code*/
section where the code should also break.
4 Answers
Reset to default 6You can use labels with the 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*/
}
Wrap the whole thing in a function, then you can simply return
to break out of both.
var input = prompt();
(function () {
while(true) {
switch(input) {
case 'hi':
break;
case 'bye':
return;
}
/*Other code*/
}
})();
It's the same answer as in C++, or most other languages. Basically, you just add a flag to tell your loop that it's 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?
Don't diminish readability in the name of "one less line 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*/
}
本文标签: javascriptBreaking out of a while loop and switch in one goStack Overflow
版权声明:本文标题:javascript - Breaking out of a while loop and switch in one go - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741436300a2378655.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论