当指定条件为真,if 语句会执行一段语句。如果条件为假,则执行另一段语句。
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
if (condition)
statement1
[else
statement2]
condition
statement1
condition
为真时执行的语句。可为任意语句,包括更深层的内部if
语句。要执行多条语句,使用块语句({ ... })将这些语句分组;若不想执行语句,则使用空语句。 statement2
condition
为假且 else
从句存在时执行的语句。可为任意语句,包括块语句和嵌套的if
语句。多层 if...else
语句可使用 else if
从句。注意:在 Javascript 中没有 elseif
(一个单词)关键字。
if (condition1) statement1 else if (condition2) statement2 else if (condition3) statement3 ... else statementN
要看看它如何工作,可以调整下嵌套的缩进:
if (condition1) statement1 else if (condition2) statement2 else if (condition3) ...
要在一个从句中执行多条语句,可使用语句块({ ... }
)。通常情况下,一直使用语句块是个好习惯,特别是在涉及嵌套if
语句的代码中:
if (condition) { statements1 } else { statements2 }
不要将原始布尔值的true
和false
与Boolean对象的真或假混淆。任何一个值,只要它不是 undefined
、null
、 0
、NaN
或空字符串(""
),那么无论是任何对象,即使是值为假的Boolean对象,在条件语句中都为真。例如:
var b = new Boolean(false);
if (b) //表达式的值为true
if...else
if (cipher_char === from_char) {
result = result + to_char;
x++;
} else {
result = result + clear_char;
}
else if
注意,Javascript中没有elseif
语句。但可以使用else
和if
中间有空格的语句:
if (x > 5) {
/* do the right thing */
} else if (x > 50) {
/* do the right thing */
} else {
/* do the right thing */
}
建议不要在条件表达式中单纯的使用赋值运算,因为粗看下赋值运算的代码很容易让人误认为是等性比较。比如,不要使用下面示例的代码:
if (x = y) {
/* do the right thing */
}
如果你需要在条件表达式中使用赋值运算,用圆括号包裹赋值运算。例如:
if ((x = y)) {
/* do the right thing */
}
Specification | Status | Comment |
---|---|---|
ECMAScript Latest Draft (ECMA-262) if statement |
Draft | |
ECMAScript 2015 (6th Edition, ECMA-262) if statement |
Standard | |
ECMAScript 5.1 (ECMA-262) if statement |
Standard | |
ECMAScript 3rd Edition (ECMA-262) if statement |
Standard | |
ECMAScript 1st Edition (ECMA-262) if statement |
Standard | Initial definition |
Desktop | Mobile | Server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
if...else | Chrome Full support Yes | Edge Full support Yes | Firefox Full support 1 | IE Full support Yes | Opera Full support Yes | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support Yes | Edge Mobile Full support Yes | Firefox Android Full support 4 | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes | nodejs Full support Yes |