是否可以在javascript中添加用于切换语句的案例?

时间:2015-08-30 03:03:49

标签: javascript switch-statement

我的问题分为三个问题:

1.它甚至可能吗?

2.如果我们可以使用默认值吗?

3.或者可以在switch语句之外执行此操作吗?

问题2的例子:

switch(stuff) {
    case 'something':
        some event;
        break;
    case 'the case that could be add by the default element':
        some event that could happen only after the code was executed
    default:
        magic code that would add another case element
}

问题3的示例:

switch(stuff) {
    case 'something':
        some event;
        break;
    case 'the case that could be add by the magic code':
        some event that could happen only after the code was executed
    default:
        some default event
}

magic code that would be executed after the switch and that would add a case

1 个答案:

答案 0 :(得分:1)

您无法对JavaScript进行真正的编码以使其自行修改,但您可以对switch语句进行编码,以便最初会忽略某些情况,然后启用""后:

var enableCase = false;

switch(true) {
    case stuff === 'something':
        // some code;
        break;
    case enableCase && stuff === 'the case not initially enabled':
        // some code
        break;
    default:
        // turn on previous case:
        enableCase = true;
        break;
}

话虽如此,我并不是真的建议这样做。根据你想要解决的根本问题,几乎可以肯定有一种更明智的方法来实现它。也许使用if / if else / else块来测试其他地方设置的标志。