How do you use the ? : (conditional) operator in JavaScript?
有人可以用简单的语言向我解释什么是?:
(有条件的“三元”)操作符以及如何使用它?
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:
if(userIsYoungerThan21) {
serveGrapeJuice();
}
else {
serveWine();
}
This can be shortened with the ?:
like so:
userIsYoungerThan21 ? serveGrapeJuice() : serveWine();
In Javascript conditional operator can evaluate to an expression, not just a statement:
var userType = userIsYoungerThan18 ? "Minor" : "Adult";
serveDrink(userIsYoungerThan21 ? "Grape Juice" : "Wine");
They can even be chained:
userIsYoungerThan4 ? serveMilk() : userIsYoungerThan21 ? serveGrapeJuice() : serveWine();
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 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.
I want to add some to the given answers.
In case you encounter (or want to use) a ternary in a situation like 'display a variable if it's set, else...', you can make it even shorter, without a ternary.
Instead of:
var welcomeMessage = 'Hello ' + (username ? username : 'guest');
You can use:
var welcomeMessage = 'Hello ' + (username || 'guest');
This is Javascripts equivallent of PHP's shorthand ternary operator ?:
Or even:
var welcomeMessage = 'Hello ' + (username || something || maybethis || 'guest');
It evaluates the variable, and if it's false or unset, it goes on to the next.
It's called the 'ternary' or 'conditional' operator.
Example
The ?: operator can be used as a shortcut for an if...else statement. It is typically used as part of a larger expression where an if...else statement would be awkward. For example:
var now = new Date();
var greeting = "Good" + ((now.getHours() > 17) ? " evening." : " day.");
The example creates a string containing "Good evening." if it is after 6pm. The equivalent code using an if...else statement would look as follows:
var now = new Date();
var greeting = "Good";
if (now.getHours() > 17)
greeting += " evening.";
else
greeting += " day.";
From MSDN JS documentation.
Basically it's a shorthand conditional statement.
Also see: