是否可以在 javascript 中将 case 添加到 switch 语句?

Is it possible to add cases to switch statement in javascript?

我的问题分为三个问题:

1.Is 甚至可能吗?

2.If 是的,我们可以使用默认值吗?

3.Or 可以在 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

您无法真正编写 JavaScript 代码使其自行修改,但您可以编写一个 switch 语句,以便最初忽略某些情况,然后 "turned on" 稍后:

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 块来测试别处设置的标志。