从 Javascript 中的 switch case 内部中断 for 循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17072605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Break for loop from inside of switch case in Javascript
提问by BASILIO
What command I must use, to get out of the for loop, also from //code inside
jump direct to //code after
我必须使用什么命令才能退出 for 循环,也可以从//code inside
直接跳转到//code after
//code before
for(var a in b)
{
switch(something)
{
case something:
{
//code inside
break;
}
}
}
//code after
采纳答案by lonesomeday
Unfortunately, Javascript doesn't have allow break
ing through multiple levels. The easiest way to do this is to leverage the power of the return
statement by creating an anonymous function:
不幸的是,Javascript 不允许break
通过多个级别。最简单的方法是return
通过创建匿名函数来利用语句的强大功能:
//code before
(function () {
for (var a in b) {
switch (something) {
case something:
{
//code inside
return;
}
}
}
}());
//code after
This works because return
leaves the function and therefore implicitly leaves the loop, moving you straight to code after
这是有效的,因为return
离开了函数,因此隐式地离开了循环,让你直接进入code after
回答by Brad Christie
回答by Chubby Boy
回答by Jeff
it depends on what you want to accomplish... one thing I commonly do is something like this:
这取决于你想完成什么......我经常做的一件事是这样的:
//code before
for(var a in b)
{
var breakFor = false;
switch(something)
{
case something:
{
//code inside
breakFor = true;
break;
}
}
if (breakFor)
break;
}
//code after
回答by Skarlinski
You can tell which loop / switch to break.
您可以判断要中断哪个循环/开关。
function foo ()
{
dance:
for(var k = 0; k < 4; k++){
for(var m = 0; m < 4; m++){
if(m == 2){
break dance;
}
}
}
}
See this answer.
看到这个答案。
回答by gest
for(var i=0; i<b.length; i++) {
switch (something) {
case 'something1':
i=b.length;
}
}
When the iteration variable i
reaches the end of the loop, it breaks. But one can force the iteration variable to reach the end of the loop.
当迭代变量i
到达循环末尾时,它会中断。但是可以强制迭代变量到达循环的末尾。
回答by Andrew_CS
I always find using conditional statements one of the easiest ways to control the code flow, at least conceptually.
我总是发现使用条件语句是控制代码流的最简单方法之一,至少在概念上是这样。
var done = false;
//code before for loop
for(var a in b){
switch(switchParameter){
case firstCase:
//code inside
done = true;
break;
}
}
if(done)
break;
}
//code outside of for loop