黄子涵

4.12 if-else语句

if 语句和 if-else 语句的语法结构如下。其中的条件表达式和语句不能省略。

// if 语句的语法

if ( 条件表达式 )
    语句

// if-else 语句的语法

if ( 条件表达式 )
     语句
else
     语句

与 if 对应的条件表达式及语句统称为 if 子句,而与 else 对应的条件表达式与语句则统称为 else 子句。可以把 if 表达式看作 if-else 表达式省略了 else 子句的特殊情况。

在条件表达式的位置所写的式子,将被求值并转换为布尔型。这一隐式的数据类型转换常常会带来各种各样的错误。

下面是一个 if-else 语句的具体示例。

// if-else语句的例子
var hzh1 = 0; 
if(hzh1 == 0) {
    console.log("if分句");
}
else {
    console.log("else分句");
}
[Running] node "e:\HMV\JavaScript\JavaScript.js"
if分句

[Done] exited with code=0 in 12.715 seconds

如果变量hzh1的值为0,则输出“if分句”,否则,输出“else分句”。

在 if 子句以及 else 子句中可以书写任意的语句。又因为 if-else 语句本身也是语句的一种,所以也能够在 if-else 语句的子句中再次使用 if-else 语句。下面是一个在 if 子句中使用 if-else 语句的例子。

// 嵌套if-else语句
var hzh2 = 0;
var hzh3 = 0;

if(hzh2 == 0) {
    if(hzh3 == 0) {
        console.log("hzh2==0 and hzh3==0");
    }
    else {
        console.log("hzh2==0 and hzh3!=0");
    } 
 }

 else
    console.log("hzh2!=0");
[Running] node "e:\HMV\JavaScript\JavaScript.js"
hzh2==0 and hzh3==0

[Done] exited with code=0 in 0.238 seconds

上面这段代码的执行结果和所预期的结果是一致的。接下来再来考虑一下没有外层 else 子句的嵌套 if-else 语句的情况。如果保持原有的缩进情况不变,将得到如下的代码。

var hzh4 = 0;
var hzh5 = 0;

if(hzh4 == 0) {
    if(hzh5 == 0) {
        console.log("hzh4==0 and hzh5==0");
    }
    else {
        console.log("hzh4==0 and hzh5!=0");
    } 
 }
[Running] node "e:\HMV\JavaScript\JavaScript.js"
hzh4==0 and hzh5==0

[Done] exited with code=0 in 0.274 seconds

也可以对其缩进进行修改,得到如下代码。

// 容易混淆的缩进
var hzh6 = 0;
var hzh7 = 0;
if (hzh6 == 0) {
    if (hzh7 == 0) {
        console.log("hzh6==0 and hzh7==0");
    }
    else
        console.log("hzh6==0 and hzh7!=0");
}
[Running] node "e:\HMV\JavaScript\JavaScript.js"
hzh6==0 and hzh7==0

[Done] exited with code=0 in 0.995 seconds

在上面的代码中,从缩进方式来看,似乎 else 子句是与外层 的 if 子句相对应的。但事实上,缩进对代码的实际意义不会产生影响。换句话说,在上述两段代码中,必然存在一组代码,其实际执行方式与代码缩进格式所暗示的方式有所不同。对于这个问题的回答是,由于 JavaScript 中有 else 子句必定与最邻近的 if 子句相结合的规则,因此在本例中,else 子句是和内层的 if 子句相对应的。这也就意味着,第二组代码的缩进方式与其实际的执行方式是不相符的。

为了避免产生这样容易混淆的情况,可以使用支持自动缩进的文本编辑器。不过,其实只要始终使用代码块来书写 if 子句和 else 子句的话,就能够避免这一问题了,所以,在此更加推荐使用这种通用性更高的解决方式。

// 通过代码块来避免出现容易使人误解的缩进

var hzh1 = 0;
var hzh2 = 0;

if(hzh1 == 0) {
    if(hzh2 == 0) {
        console.log("hzh1 == 0 和 hzh2 == 0");
    } else {
        console.log("hzh1 == 0 和 hzh2 != 0");
    }
}
[Running] node "e:\HMV\Babel\hzh.js"
hzh1 == 0 和 hzh2 == 0

[Done] exited with code=0 in 0.361 seconds

按照自己的习惯就好,这部分省略。

posted @ 2022-05-27 17:43  黄子涵  阅读(230)  评论(0编辑  收藏  举报