★ wanayoo — archive 1999 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/if...elseNouvelle recherche | Portail wanayoo

if...else

1 位贡献者:
 

概览

当指定条件为true时会执行 if 语句 会执行一条语句.如果该条件为false,则执行另一条语句.

语法

if (condition)
   statement1
[else
   statement2]
condition
值为true或false的表达式.
statement1
如果条件值为true时执行的语句. 可为任意语句, 包括更深层的内部if语句. 要执行多条语句,使用 block 语句 ({ ... }) 将这些语句分组, 若不想执行语句则使用 empty 语句.
statement2
如果条件值为false且else从句存在时执行的语句. 可为任意语句, 包括语句块和更深层的内部if语句.

说明

多层 if...else 语句可使用 else if 从句. 注意,在JavaScript中没有 elseif (一个单词)关键字.

if (condition1)
   statement1
else if (condition2)
   statement2
else if (condition3)
   statement3
...
else
   statementN

下面是合理排版的嵌套if语句:

if (condition1)
   statement1
else
   if (condition2)
      statement2
   else
      if (condition3)
...

要在一个从句中执行多条语句,可使用语句块 ({ ... }) . 通常情况下,一直使用语句块是个好习惯, 特别是有内部if语句的嵌套的情况:

if (condition) {
   statements1
} else {
   statements2
}

不要被原生boolean值value和false与 Boolean 对象的true和false值迷惑. 所有不是 undefined, null, 0, NaN, 空字符串 (""), 以及任意对象, 包括值为false的Boolean对象, 在条件语句中都为true. 例如:

var b = new Boolean(false);
if (b) // this condition evaluates to 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) {

} else if (x > 50) {

} else {

}

例子: 条件表达式中的赋值语句

建议不要再条件表达式中单纯的使用赋值语句, 因为粗看下赋值语句的代码很容易让人误认为是等性语句. 比如,不要使用下面示例的代码:

if (x = y) {
   /* do the right thing */
}

如果你需要在条件表达式中使用赋值语句, 用圆括号包裹赋值语句. 比如:

if ((x = y)) {
   /* do the right thing */
}

规范

Specification Status Comment
ECMAScript 1st Edition. Standard Initial definition.
ECMAScript 5.1 (ECMA-262)
if statement
Standard  
ECMAScript 6 (ECMA-262)
if statement
Release Candidate  

浏览器兼容性

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) (Yes) (Yes) (Yes)
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)

相关链接

文档标签和贡献者

向此页面作出贡献: yenshen
最后编辑者: yenshen,
隐藏侧边栏