JS中嵌套三元运算符的替代方法 [英] Alternative to nested ternary operator in JS
问题描述
我个人很喜欢三元运算符,以我的拙见,它们使复杂的表达式非常易于理解。以这个为例:
I personally love ternary operators, and in my humble opinion, they make complicated expressions very easy to digest. Take this one:
word = (res.distance === 0) ? 'a'
: (res.distance === 1 && res.difference > 3) ? 'b'
: (res.distance === 2 && res.difference > 5 && String(res.key).length > 5) ? 'c'
: 'd';
但是在我们项目的ESLINT规则中,禁止嵌套三元运算符,因此我必须摆脱上面的内容
However in our project's ESLINT rules nested ternary operators are forbidden, so I have to get rid of the above.
我正在尝试寻找这种方法的替代方法。我真的不想把它变成一个很大的if / else语句,但是不知道是否还有其他选择。
I'm trying to find out alternatives to this approach. I really don't want to turn it into a huge if / else statement, but don't know if there's any other options.
推荐答案
这里的替代方案基本上是:
Your alternatives here are basically:
- 如果
/
其他
您不想执行的操作 - 一个
开关
和如果
/else
- That
if
/else
you don't want to do - A
switch
combined withif
/else
我尝试过提出一个合理的查找映射选项,但很快就变得不合理了。
I tried to come up with a reasonable lookup map option, but it got unreasonable fairly quickly.
我会选择#1,它并不大:
I'd go for #1, it's not that big:
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 all the braces and vertical size bother you, without them it's almost as concise as the conditional operator version:
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
,但是其他人具有不同的样式角度。)
(I'm not advocating that, I never advocate leaving off braces or putting the statement following an if
on the same line, but others have different style perspectives.)
#2在我看来,它比较笨拙,但这可能是比其他任何东西都更时尚的注释:
#2 is, to my mind, more clunky but that's probably more a style comment than anything else:
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的开关
在 B 语法语言族: case
语句可以是表达式,并与源代码顺序中的开关值匹配:
And finally, and I am not advocating this, you can take advantage of the fact that JavaScript's switch
is unusual in the B-syntax language family: The case
statements can be expressions, and are matched against the switch value in source code order:
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;
}
那有多丑? :-)
这篇关于JS中嵌套三元运算符的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!