if
statement
执行语句若指定条件为
truthy
。若条件为
falsy
,可以执行另一语句。
if (condition) statement1 [else statement2]
condition
statement1
if
statements. To execute multiple statements, use a
block
statement (
{ ... }
) to group those statements. To execute no statements, use an
empty
语句。
statement2
condition
is
falsy
和
else
clause exists. Can be any statement, including block statements and further nested
if
语句。
多
if...else
语句可以嵌套以创建
else if
子句。注意,没有
elseif
(in one word) keyword in JavaScript.
if (condition1) statement1 else if (condition2) statement2 else if (condition3) statement3 ... else statementN
To see how this works, this is how it would look if the nesting were properly indented:
if (condition1)
statement1
else
if (condition2)
statement2
else
if (condition3)
...
To execute multiple statements within a clause, use a block statement (
{ ... }
) to group those statements. In general, it is a good practice to always use block statements, especially in code involving nested
if
statements:
if (condition) {
statements1
} else {
statements2
}
Do not confuse the primitive Boolean values
true
and
false
with truthiness or falsiness of the
布尔
object. Any value that is not
false
,
undefined
,
null
,
0
,
-0
,
NaN
, or the empty string (
""
), and any object, including a Boolean object whose value is
false
, is considered
truthy
when used as the condition. For example:
var b = new Boolean(false); if (b) // this condition is truthy
if (cipher_char === from_char) {
result = result + to_char;
x++;
} else {
result = result + clear_char;
}
注意,没有
elseif
句法在 JavaScript。不管怎样,可以编写它采用空格介于
else
and
if
:
if (x > 50) {
/* do something */
} else if (x > 5) {
/* do something */
} else {
/* do something */
}
It is advisable to not use simple assignments in a conditional expression, because the assignment can be confused with equality when glancing over the code. For example, do not use the following code:
if (x = y) {
/* do something */
}
If you need to use an assignment in a conditional expression, a common practice is to put additional parentheses around the assignment. For example:
if ((x = y)) {
/* do something */
}
| 规范 |
|---|
|
ECMAScript (ECMA-262)
在该规范中的 if statement 定义。 |
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
if...else
|
Chrome 1 | Edge 12 | Firefox 1 | IE 3 | Opera 3 | Safari 1 | WebView Android 1 | Chrome Android 18 | Firefox Android 4 | Opera Android 10.1 | Safari iOS 1 | Samsung Internet Android 1.0 | nodejs 0.1.100 |
完整支持