您的替代方案基本上是:
你不想做
那个 if / else
A switch 与 if / else 合并
我试图提出一个合理的查找映射选项,但它很快就变得不合理了 .
我会去#1,它不是那么大:
if (res.distance == 0) {
word = 'a';
} else if (res.distance == 1 && res.difference > 3) {
word = 'b';
} else if (res.distance == 2 && res.difference > 5 && String(res.key).length > 5) {
word = 'c';
} else {
word = 'd';
}
如果所有的大括号和垂直大小都打扰你,没有它们,它几乎与条件运算符版本一样简洁:
if (res.distance == 0) word = 'a';
else if (res.distance == 1 && res.difference > 3) word = 'b';
else if (res.distance == 2 && res.difference > 5 && String(res.key).length > 5) word = 'c';
else word = 'd';
(我不是在提倡这一点,我从不主张在同一条线上放下大括号或将声明放在 if 之后,但其他人则有不同的风格观点 . )
在我看来,#2更笨重,但这可能更像是一种风格评论而不是其他任何东西:
word = 'd';
switch (res.distance) {
case 0:
word = 'a';
break;
case 1:
if (res.difference > 3) {
word = 'b';
}
break;
case 2:
if (res.difference > 5 && String(res.key).length > 5) {
word = 'c';
}
break;
}
最后,我赞成这一点,你可以利用JavaScript的 switch 在B -syntax语言族中不常见的事实: case 语句可以是表达式,并且与源代码顺序中的switch值匹配:
switch (true) {
case res.distance == 0:
word = 'a';
break;
case res.distance == 1 && res.difference > 3:
word = 'b';
break;
case res.distance == 2 && res.difference > 5 && String(res.key).length > 5:
word = 'c';
break;
default:
word = 'd';
break;
}
这有多难啊? :-)