7
switch ("B")
{
case "A":
    break;
case "B":
    continue;
case "C":
    break;
default:
    break;
}

simple correct code in C++, but when made in javascript in stable chrome it just throws an error "Illegal continue statement", looks like continue statement is just disallowed in switch in javascript... Heard about return but it just returns and doesnt continue... So is there a way to continue switch in js?

4

6 回答 6

12

continue与 es 完全无关,与switchJavascript和 C++无关:

int main()
{
    int x = 5, y = 0;
    switch (x) {
        case 1:
            continue;
        case 2:
            break;
        default:
            y = 4;
    }
}

错误:继续语句不在循环内

如果您想摆脱这种情况,请使用break; 否则,允许案件通过:

switch ("B")
{
    case "A":
        break;
    case "B":
    case "C":
        break;
    default:
        break;
}

如果您正在寻找跳转到下一个案例的快捷方式,那么,不,您不能这样做。

switch ("B")
{
    case "A":
        break;
    case "B":
        if (something) {
           continue; // nope, sorry, can't do this; use an else
        }

        // lots of code
    case "C":
        break;
    default:
        break;
}
于 2013-08-06T10:12:02.397 回答
10

我相信你可以通过使用标记的无限循环来模拟你想要的:

var a = "B";
loop: while( true ) {
    switch (a)
    {
    case "A":
        break loop;
    case "B":
        a = "C";
        continue loop;
    case "C":
        break loop;
    default:
        break loop;
    }
}

否则,您应该考虑以其他方式表达您想要的东西。

即使你能做到这一点,这将是一个巨大的 WTF。只需使用 if else if。

于 2013-08-06T10:01:56.253 回答
3

我想你的意思是:

switch ("B")
{
    case "A":
        break;
    case "B":
    case "C":
        break;
    default:
        break;
}

没有必要continue。当 B 来时,它会移动到 C。

于 2013-08-06T09:43:27.173 回答
0

没有该语句的 switch casebreak将“落入”(正如它所说的那样)到下一个。省略break将使代码的行为像您所说的那样,因为它是 switch 语句的默认/隐式行为。

continue语句的使用是为循环保留的,它的作用实际上与您想要的略有不同;它将中断循环的当前迭代并继续下一个迭代,重新评估循环条件。

于 2013-08-06T09:56:55.243 回答
0

实际上你可以在 switch 内部循环中使用它,在这种情况下 break/continue 是一个有用的组合

看看这个例子

var array = [1, 2, "I am a string", function(){}, {}, 1,2,3]
for(let i in array){
    switch(typeof array[i]) {
    case "number":
        array[i] += " I was a number"
        break; // break from the switch but go on in the for-loop
               // ie. go to *put esclamation mark*
    case "function":
        array[i] = "function"
        // fall through
    default:
        array[i] = `this is a ${JSON.stringify(array[i])} object`
        break; // also here goes to *put esclamation mark*
    case "string":
        continue; // continue with the next iteration of the loop
                  // ie. do not put exclamation mark in this case
    }
    array[i] += "!" // *put esclamation mark*
}
/*
array will become
[ "1 I was a number!", "2 I was a number!", "I am a string", "this is a \"function\" object!", "this is a {} object!", "1 I was a number!", "2 I was a number!", "3 I was a number!" ]
*/
于 2020-02-19T17:19:00.937 回答
-1

继续可能只指循环。它不能在 switch 语句中使用。无论如何,你期望它有什么行为?

于 2013-08-06T09:24:44.287 回答