我的问题分为三个问题:
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
最佳答案
您无法真正编写 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 block 来测试其他地方设置的标志。
关于javascript - 是否可以在 JavaScript 中添加 case 到 switch 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32292754/