gpt4 book ai didi

javascript - 是否有可能以某种方式缩短 switch 语句?也许有一个循环?

转载 作者:太空宇宙 更新时间:2023-11-04 07:33:59 25 4
gpt4 key购买 nike

无论使用哪种编程语言,有哪些选项可以缩短具有许多类似情况的长 switch 语句?

根据我的搜索,我找到了类似 this one 的答案但我的情况各不相同,只有一个整数在循环中变化。

我经常在 bash/PHP/Python/JavaScript 中使用以下 switch 语句构造,我正在寻找更短的版本:

switch ($device) {
// 2ghz
case "n2":
return 1;
break;
case "nne2":
return 2;
break;
case "ne2":
return 3;
break;
case "ene2":
return 4;
break;
case "e2":
return 5;
break;
case "ese2":
return 6;
break;
case "se2":
return 7;
break;
case "sse2":
return 8;
break;
case "s2":
return 9;
break;
case "ssw2":
return 10;
break;
case "sw2":
return 11;
break;
case "wsw2":
return 12;
break;
case "w2":
return 13;
break;
case "wnw2":
return 14;
break;
case "nw2":
return 15;
break;
case "nnw2":
return 16;
break;

// 5ghz
case "n5":
return 17;
break;
case "nne5":
return 18;
break;
case "ne5":
return 19;
break;
case "ene5":
return 20;
break;
case "e5":
return 21;
break;
case "ese5":
return 22;
break;
case "se5":
return 23;
break;
case "sse5":
return 24;
break;
case "s5":
return 25;
break;
case "ssw5":
return 26;
break;
case "sw5":
return 27;
break;
case "wsw5":
return 28;
break;
case "w5":
return 29;
break;
case "wnw5":
return 30;
break;
case "nw5":
return 31;
break;
case "nnw5":
return 32;
break;

// 24ghz
case "n24":
return 33;
break;
case "nne24":
return 34;
break;
case "ne24":
return 35;
break;
case "ene24":
return 36;
break;
case "e24":
return 37;
break;
case "ese24":
return 38;
break;
case "se24":
return 39;
break;
case "sse24":
return 40;
break;
case "s24":
return 41;
break;
case "ssw24":
return 42;
break;
case "sw24":
return 43;
break;
case "wsw24":
return 44;
break;
case "w24":
return 45;
break;
case "wnw24":
return 46;
break;
case "nw24":
return 47;
break;
case "nnw24":
return 48;
break;

default:
return 0;
break;
}

最佳答案

在 Python 中你可以使用像这样简单的东西,如果你的返回值很简单的话:

items = ["n2","nne2","ne2","ene2", ...]
for idx, key in enumerate(items, start=1):
if device == key:
result = idx
result = 0

或者如果您希望返回值更复杂:

my_dict = {
"n2": 1,
"nne2": 2,
"ne2": 3,
"ene2": 4,
...}

for key, value in my_dict.items():
if device == key:
result = value
result = 0

关于javascript - 是否有可能以某种方式缩短 switch 语句?也许有一个循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40786149/

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