What does this syntax mean? [duplicate]
Possible Duplicate:
Question mark in JavaScript
I've seen this around a开发者_运维知识库 few times but I never knew what it meant. What is the name of it and how does it work?
Here is the example I saw:
input.checked = input.type == "radio" ? true : false;
That example has an extra =
in it, I think you meant:
input.checked = input.type == "radio" ? true : false;
(It's fixed now.)
It assigns true
to input.checked
if input.type == "radio"
, or false
if it doesn't.
That
expression ? trueResult : falseResult
...is called the conditional operator (or sometimes, the "ternary" operator — technically, it's just a ternary operator, e.g., an operator that takes three operands). More in Section 11.12 in the spec.
In this case, there's absolutely no point in using the conditional operator, because the result of the equivalence expression is true
or false
anyway, so it could be written just:
input.checked = input.type == "radio";
...but there are lots of places where the conditional operator is useful. For instance, suppose you wanted to assign 1
or 2
to x
depending on whether y
was 42:
x = y == 42 ? 1 : 2;
You can think of the ?
as asking a yes-or-no question, with what follows it being the "yes" answer, and what follows the :
being the "no" answer.
Maybe it's easier to understand like this:
input.checked = (input.type == "radio")? true : false;
It's basically an if else. If the expression is true then input.checked will be set to the first value, else the second value.
[edit]
As a note, in JavaScript, you should always use '===' instead of '==' when evaluating strings to check type equality as well.
This is a ternary expression. It is a shorthand for:
if (input.type == "radio") {
input.checked = true;
} else {
input.checked = false;
}
However, there is redundancy in this particular example. It could have been simply written as:
input.checked = input.type == "radio";
Maybe the first ==
is =
?
It looks like ternary operator. (short else-if structure)
精彩评论