你如何使用?: JavaScript 中的(条件)运算符?
简单来说,?:
(条件,三元")运算符是什么?如何使用它?
In simple words, what is the ?:
(conditional, "ternary") operator and how can I use it?
推荐答案
这是 if-else 语句的单行简写.它被称为条件运算符.1
This is a one-line shorthand for an if-else statement. It's called the conditional operator.1
这是一个可以使用条件运算符缩短的代码示例:
Here is an example of code that could be shortened with the conditional operator:
var userType;
if (userIsYoungerThan18) {
userType = "Minor";
} else {
userType = "Adult";
}
if (userIsYoungerThan21) {
serveDrink("Grape Juice");
} else {
serveDrink("Wine");
}
这可以用 ?:
缩短,如下所示:
This can be shortened with the ?:
like so:
var userType = userIsYoungerThan18 ? "Minor" : "Adult";
serveDrink(userIsYoungerThan21 ? "Grape Juice" : "Wine");
像所有表达式一样,条件运算符也可以用作具有副作用的独立语句,尽管这是 不寻常在缩小之外:
Like all expressions, the conditional operator can also be used as a standalone statement with side-effects, though this is unusual outside of minification:
userIsYoungerThan21 ? serveGrapeJuice() : serveWine();
他们甚至可以被锁住:
serveDrink(userIsYoungerThan4 ? 'Milk' : userIsYoungerThan21 ? 'Grape Juice' : 'Wine');
不过要小心,否则你会得到这样的复杂代码:
Be careful, though, or you will end up with convoluted code like this:
var k = a ? (b ? (c ? d : e) : (d ? e : f)) : f ? (g ? h : i) : j;
<小时>
1 通常称为三元运算符",但实际上它只是a三元运算符[接受三个操作数的运算符].不过,它是 JavaScript 目前唯一拥有的.
1 Often called "the ternary operator," but in fact it's just a ternary operator [an operator accepting three operands]. It's the only one JavaScript currently has, though.
相关文章