可以将"else if"与三元运算符一起使用吗? [英] can I use `else if` with a ternary operator?
问题描述
我只能在三元运算符语法的语句中使用if
和else
还是可以以某种方式包含else if
?
Can I only use if
and else
in a statement in ternary operator syntax or can I also somehow include an else if
?
示例:
if(a) {
x
}
else if(y) {
c
}
else {
b
}
推荐答案
与具有可选else
或可选else if
分支的if
不同,三元运算符具有两个且只有两个分支.
Unlike an if
with optional else
or optional else if
branches, a ternary operator has two and only two branches.
如果您对第二个子句进行分支,则可以具有类似else if
的功能:
You can have else if
like functionality if you sub-branch the second clause:
a ? b : (c ? d : e)
这通常不是一个好主意,因为三元操作开始时可能会很麻烦,并且像这样进行分层通常是对难以维护的代码的一种快速训练.
This is usually a bad idea as ternary operations can be messy to start with and layering like this is usually an express train to unmaintainable code.
最好写:
if (a) {
b
}
else if (c) {
{
d
}
else {
e
}
这比较冗长,但很清楚.
This is more verbose, but abundantly clear.
如果过于激进地使用三元,您将得到如下代码:
If you use ternaries too agressively you'll end up with code like:
a()?c?d?e:f:g:h?i(j?k:l?m:n):o
任何人都在猜测那里发生了什么.
Where it's anyone's guess what's going on in there.
这篇关于可以将"else if"与三元运算符一起使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!