javascript 我可以将`else if` 与三元运算符一起使用吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47126232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:13:26  来源:igfitidea点击:

can I use `else if` with a ternary operator?

javascriptecmascript-6

提问by lologic

Can I only use ifand elsein a statement in ternary operator syntax or can I also somehow include an else if?

我可以只在三元运算符语法的语句中使用ifandelse还是我也可以以某种方式包含else if?

example:

例子:

if(a) {
   x
}
else if(y) {
   c
}
else {
   b
}

回答by tadman

Unlike an ifwith optional elseor optional else ifbranches, a ternary operator has two and only two branches.

ifwith optionalelse或 optionalelse if分支不同,三元运算符有两个且只有两个分支。

You can have else iflike functionality if you sub-branch the second clause:

else if如果您将第二个子句作为分支,您可以拥有类似的功能:

a ? b : (c ? d : e)

This is usually a bad ideaas ternary operations can be messy to start with and layering like this is usually an express train to unmaintainable code.

这通常是一个坏主意,因为三元运算开始时可能很混乱,而且像这样的分层通常是无法维护代码的快速列车。

It is much better to write:

最好这样写:

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.

任何人都可以猜测那里发生了什么。

回答by Basti

You could stack multiple ternaries:

您可以堆叠多个三元组:

var x = (y) ? 1 : ( (z) ? 2 : 0 );