当指定条件为真,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 - 值为真或假的 表达式
-
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 |
浏览器兼容
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out
https://github.com/mdn/browser-compat-data and send us a pull request.
Update compatibility data on GitHub
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
if...else |
Chrome Full support 1 | Edge Full support 12 | Firefox Full support 1 | IE Full support 3 | Opera Full support Yes | Safari Full support Yes | WebView Android Full support 1 | Chrome Android Full support 18 | Firefox Android Full support 4 | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support 1.0 | nodejs Full support Yes |
Legend
- Full support
- Full support