JavaScript 中的 Else If

JavaScript 中的 Else If 在我们需要检查多个条件时非常有用。我们也可以使用嵌套的 If 来实现同样的效果。但是,随着条件数量的增加,代码的复杂性也会增加。

Else If 语法

Else If 语句的语法如下:

if (condition1)
       statements 1
else if (condition2)
       statements 2
else if (condition3)
       statements 3
      ...........
else if (conditionn)
       statements n
else
      default statements

JavaScript Else If 语句通过顺序执行多个表达式来有效处理它们。它将检查第一个条件。如果表达式的计算结果为 TRUE,它将执行该块中存在的代码行。如果表达式的计算结果为 FALSE,它将检查下一个(Else If 条件),依此类推。

在 Else If 语句中,在某些情况下 condition1、condition2 为 TRUE,例如:x = 20,y = 10

条件1:x > y //TRUE

条件2:x != y //TRUE

在这些情况下,将执行 Condition1 下的代码。因为 ELSE IF 条件只有在其之前的 IF 语句失败时才会执行。

JavaScript 中的 Else If 示例

在此程序中,我们将使用 Else if 语句计算他是否有资格获得奖学金。

<!DOCTYPE html>
<html>
<head>
    <title>ElseIfinJavaScript</title>
</head>
 <h1>ElseIfinJavaScript</h1>
<body>
<script>
    var Totalmarks = 380;
    if (Totalmarks >= 540)
    {
        document.write("<b> Congratulations </b>"); 
        document.write("<br\> You are eligible for Full Scholarship " ); 
    }
    else if(Totalmarks >= 480)
    {
        document.write("<b> Congratulations </b>"); 
        document.write("<br\> You are eligible for 50 Percent Scholarship " ); 
    }
    else if (Totalmarks >= 400)
    {
        document.write("<b> Congratulations </b>"); 
        document.write("<br\> You are eligible for 10 Percent Scholarship " ); 
    }
    else
    {
        document.write("<b> You are Not eligible for Scholarship </b>");
        document.write("<br\> We are really Sorry for You" );    
    }
</script>
</body>
</html>

输出 1:在此 JS 示例中,Totalmarks= 550。首先,If 条件为 TRUE;这就是为什么 If 语句中的代码显示为浏览器输出。

Else If Statement 1

输出 2:为了演示 JavaScript Else if 语句,我们将 Totalmarks 更改为 500,这意味着第一个 IF 条件为 FALSE。它将检查 (Totalmarks >= 480),这为 TRUE,以显示此块中的行。尽管 (Total marks >= 400) 条件为 TRUE,但它不会检查该表达式。

Congratulations
You are eligible for 50 Percent Scholarship

输出 3:我们将 Totalmarks 更改为 440,这意味着第一个 IF 条件 (Total marks = 480) 为 FALSE。因此,它将检查 (Totalmarks >= 400),这为 TRUE,以打印此块中的代码。

Congratulations
You are eligible for 10 Percent Scholarship

输出 4:我们将 Totalmarks 更改为 380,这意味着所有 IF 表达式都失败。因此,它将打印 else 块中的代码。

You are Not eligible for Scholarship
We are really Sorry for You