if-else 语句的简写 [英] Shorthand for if-else statement
问题描述
我有一些代码有很多类似这样的 if/else 语句:
I have some code with a lot of if/else statements similar to this:
var name = "true";
if (name == "true") {
var hasName = 'Y';
} else if (name == "false") {
var hasName = 'N';
};
但是有没有办法让这些语句更短?类似 的东西?真":假"
...
But is there a way to make these statements shorter? Something like ? "true" : "false"
...
推荐答案
Using the ternary :?
operator [spec].
var hasName = (name === 'true') ? 'Y' :'N';
三元运算符让我们可以按照您的需要编写速记 if..else
语句.
The ternary operator lets us write shorthand if..else
statements exactly like you want.
看起来像:
(name === 'true')
- 我们的条件
?
- 三元运算符本身
'Y'
- 条件评估为真时的结果
'Y'
- the result if the condition evaluates to true
'N'
- 如果条件评估为假的结果
'N'
- the result if the condition evaluates to false
所以简而言之 (question)?(result if true):(result is false)
,如您所见 - 它返回表达式的值,因此我们可以简单地将其分配给一个变量就像上面的例子一样.
So in short (question)?(result if true):(result is false)
, as you can see - it returns the value of the expression so we can simply assign it to a variable just like in the example above.
这篇关于if-else 语句的简写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!