gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 09:01:23 25 4
gpt4 key购买 nike

我的问题分为三个问题:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com