Javascript 一行 If...else...else if 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29043135/
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
Javascript one line If...else...else if statement
提问by Sam Perlmutter
I know you can set variables with one line if/else statements by doing var variable = (condition) ? (true block) : (else block), but I was wondering if there was a way to put an else if statement in there. Any suggestions would be appreciated, thanks everyone!
我知道您可以通过执行在一行 if/else 语句中设置变量var variable = (condition) ? (true block) : (else block),但我想知道是否有办法在其中放置 else if 语句。任何建议将不胜感激,谢谢大家!
回答by Gremash
Sure, you can do nested ternary operators but they are hard to read.
当然,您可以使用嵌套的三元运算符,但它们很难阅读。
var variable = (condition) ? (true block) : ((condition2) ? (true block2) : (else block2))
回答by Qwerty
tl;dr
tl;博士
Yes, you can...If a then a, else if b then if c then c(b), else b, else null
是的,你可以......如果a然后a,否则如果b那么如果c那么c(b),否则b,否则为空
a ? a : (b ? (c ? c(b) : b) : null)
a
? a
: b
? c
? c(b)
: b
: null
longer version
更长的版本
Ternary operator ?:used as inline if-else is right associative. In short this means that the rightmost ?gets fed first and it takes exactly oneclosest operand on the left and two, with a :, on the right.
?:用作内联 if-else 的三元运算符是右结合的。简而言之,这意味着最右边的?首先被馈送,并且它在左边恰好需要一个最接近的操作数,在右边需要两个, 和 a :。
Practically speaking, consider the following statement (same as above):
实际上,请考虑以下语句(同上):
a ? a : b ? c ? c(b) : b : null
a ? a : b ? c ? c(b) : b : null
The rightmost ?gets fed first, so find it and its surrounding three argumentsand consecutively expand to the left to another ?.
最右边的先?被喂食,所以找到它和它周围的三个参数,并连续向左扩展到另一个?。
a ? a : b ? c ? c(b) : b : null
^ <---- RTL
1. |1-?-2----:-3|
^ <-
2. |1-?|--2---------|:-3---|
^ <-
3.|1-?-2-:|--3--------------------|
result: a ? a : (b ? (c ? c(b) : b) : null)
This is how computers read it:
计算机是这样读的:
- Term
ais read.
Node:a- Nonterminal
?is read.
Node:a ?- Term
ais read.
Node:a ? a- Nonterminal
:is read.
Node:a ? a :- Term
bis read.
Node:a ? a : b- Nonterminal
?is read, triggering the right-associativity rule. Associativity decides:
node:a ? a : (b ?- Term
cis read.
Node:a ? a : (b ? c- Nonterminal
?is read, re-applying the right-associativity rule.
Node:a ? a : (b ? (c ?- Term
c(b)is read.
Node:a ? a : (b ? (c ? c(b)- Nonterminal
:is read.
Node:a ? a : (b ? (c ? c(b) :- Term
bis read.
Node:a ? a : (b ? (c ? c(b) : b- Nonterminal
:is read. The ternary operator?:from previous scope is satisfied and the scope is closed.
Node:a ? a : (b ? (c ? c(b) : b) :- Term
nullis read.
Node:a ? a : (b ? (c ? c(b) : b) : null- No tokens to read. Close remaining open parenthesis.
Result is:
a ? a : (b ? (c ? c(b) : b) : null)
- 条款
a已读。
节点:a?读取非终结符。
节点:a ?- 条款
a已读。
节点:a ? a:读取非终结符。
节点:a ? a :- 条款
b已读。
节点:a ? a : b?读取非终结符,触发右结合规则。关联性决定:
节点:a ? a : (b ?- 条款
c已读。
节点:a ? a : (b ? c?读取非终结符,重新应用右结合规则。
节点:a ? a : (b ? (c ?- 条款
c(b)已读。
节点:a ? a : (b ? (c ? c(b):读取非终结符。
节点:a ? a : (b ? (c ? c(b) :- 条款
b已读。
节点:a ? a : (b ? (c ? c(b) : b:读取非终结符。?:前一个作用域的三元运算符得到满足,作用域关闭。
节点:a ? a : (b ? (c ? c(b) : b) :- 条款
null已读。
节点:a ? a : (b ? (c ? c(b) : b) : null- 没有要阅读的令牌。关闭剩余的左括号。
结果是:
a ? a : (b ? (c ? c(b) : b) : null)
Better readability
更好的可读性
The ugly oneliner from above could (and should)be rewritten for readability as:
(Note that the indentation does notimplicitly define correct closures as brackets () do.)
上面丑陋的 oneliner 可以(并且应该)为了可读性而重写为:(
请注意,缩进并没有像括号 () 那样隐式定义正确的闭包。)
a
? a
: b
? c
? c(b)
: b
: null
for example
例如
return a + some_lengthy_variable_name > another_variable
? "yep"
: "nop"
More reading
更多阅读
Mozilla: JavaScript Conditional Operator
Wiki: Operator Associativity
Mozilla:JavaScript 条件运算符
Wiki:运算符关联性
Bonus: Logical operators
奖励:逻辑运算符
var a = 0 // 1
var b = 20
var c = null // x=> {console.log('b is', x); return true} // return true here!
a
&& a
|| b
&& c
&& c(b) // if this returns false, || b is processed
|| b
|| null
Using logical operators as in this example is ugly and wrong, but this is where they shine...
在这个例子中使用逻辑运算符是丑陋和错误的,但这就是它们的亮点......
"Null coalescence"
“零聚结”
This approach comes with subtle limitations as explained in the link below. For proper solution, see Nullish coalescing in Bonus2.
这种方法带有细微的限制,如下面的链接中所述。有关正确的解决方案,请参阅 Bonus2 中的 Nullish 合并。
function f(mayBeNullOrFalsy) {
var cantBeNull = mayBeNullOrFalsy || 42 // "default" value
var alsoCantBe = mayBeNullOrFalsy ? mayBeNullOrFalsy : 42 // ugly...
..
}
Short-circuit evaluation
短路评估
false && (anything) // is short-circuit evaluated to false.
true || (anything) // is short-circuit evaluated to true.
Logical operators
Null coalescence
Short-circuit evaluation
Bonus2: new in JS
Bonus2:JS 中的新功能
Proper "Nullish coalescing"
正确的“空合并”
developer.mozilla.org~Nullish_coalescing_operator
developer.mozilla.org~Nullish_coalescing_operator
function f(mayBeNullOrUndefined) {
var cantBeNullOrUndefined = mayBeNullOrUndefined ?? 42
..
}
Optional chaining
可选链
https://github.com/tc39/proposal-optional-chaining
https://github.com/tc39/proposal-optional-chaining
// before
var street = user.address && user.address.street
// after
var street = user?.address.street
// combined with Nullish coalescing
// before
var street = user.address
? user.address.street
: "N/A"
// after
var street = user?.address.street ?? "N/A"
回答by Masood
In simple words:
简单来说:
var x = (day == "yes") ? "Good Day!" : (day == "no") ? "Good Night!" : "";
回答by MyLilMulePepe
I know this is an old thread, but thought I'd put my two cents in. Ternary operators are able to be nested in the following fashion:
我知道这是一个旧线程,但我想我会投入我的两分钱。三元运算符能够以以下方式嵌套:
var variable = conditionA ? valueA : (conditionB ? valueB: (conditionC ? valueC : valueD));
Example:
例子:
var answer = value === 'foo' ? 1 :
(value === 'bar' ? 2 :
(value === 'foobar' ? 3 : 0));
回答by Piotr Dajlido
This is use mostly for assigning variable, and it uses binomial conditioning eg.
这主要用于分配变量,它使用二项式条件,例如。
var time = Date().getHours(); // or something
var clockTime = time > 12 ? 'PM' : 'AM' ;
There is no ElseIf, for the sake of development don't use chaining, you can use switchwhich is much faster if you have multiple conditioning in .js
没有 ElseIf,为了开发,不要使用链接,switch如果你在 .js 中有多个条件,你可以使用哪个更快
回答by E_d
You can chain as much conditions as you want. If you do:
您可以根据需要链接尽可能多的条件。如果你这样做:
var x = (false)?("1true"):((true)?"2true":"2false");
You will get x="2true"
你会得到 x="2true"
So it could be expressed as:
所以可以表示为:
var variable = (condition) ? (true block) : ((condition)?(true block):(false block))
回答by BBB.CCC
a === "a" ? do something
: a === "b" ? do something
: do something

