将 If 语句嵌入到另一个 If 语句中称为 JavaScript 嵌套 If 语句。JavaScript Else 语句允许我们根据表达式的结果(TRUE、FALSE)打印不同的语句。有时,当条件为 TRUE 时,我们需要进一步检查。在这种情况下,我们可以使用嵌套 IF 语句,但使用时要小心。
例如,每个人如果年满 18 岁或以上则有资格工作,否则则不合格。但是,公司不会给每个人都提供工作。因此,我们使用另一个 If 语句,也称为 JavaScript 嵌套 If 语句,来检查他们的教育资格或任何公司特定要求。
JavaScript 嵌套 If 语法
此编程语言中的嵌套 If 语法如下
if ( test condition 1)
{
//If the test condition 1 is TRUE then these it will check for test condition 2
if ( test condition 2)
{
//If the test condition 2 is TRUE then these statements will be executed
Test condition 2 True statements;
}
else
{
//If the c test condition 2 is FALSE then these statements will be executed
Test condition 2 False statements;
}
else
{
//If the test condition 1 is FALSE then these statements will be executed
Test condition 1 False statements;
}
JavaScript 嵌套 If 的流程图
让我们看一下嵌套 If 的流程图以获得更好的理解。

如果测试条件 1 为 FALSE,则执行 STATEMENT3。如果测试条件 1 为 TRUE,则它将检查测试条件 2,如果为 TRUE,则执行 STATEMENT1,否则执行 STATEMENT2。
JavaScript 嵌套 If 示例
在此嵌套 If 示例程序中,我们将声明一个变量 age 并存储默认值。
如果年龄小于 18 岁,我们将打印两条语句。当条件失败时,我们将检查另一个条件(嵌套),如果成功,我们将写一些内容。如果嵌套条件失败,我们将打印其他内容。请参考 JavaScript 中的 JavaScript If Else 语句。
<!DOCTYPE html>
<html>
<head>
<title> JavaScriptElseStatement </title>
</head>
<h1> JavaScriptElseStatement </h1>
<body>
<script>
var age = 15;
if( age < 18 )
{
document.write("<b> You are Minor. </b>");
document.write("<br\> Not Eligible to Work " );
}
else
{
if (age >= 18 && age <= 60 )
{
document.write("<b> You are Eligible to Work. </b>");
document.write("<br\> Please fill in your details and apply " );
}
else
{
document.write("<b> You are too old to work as per the Government rules </b>");
document.write("<br\> Please Collect your pension!" );
}
}
</script>
</body>
</html>
在此 JavaScript 嵌套 If 语句示例中,如果某人年龄小于 18 岁,则他们没有工作资格。如果某人年龄大于或等于 18 岁,则第一个条件失败。它将检查 else 语句。
在 Else 语句中,有一个名为 Nested If 的另一个 if 条件。
- JS 嵌套 IF 语句将检查此人的年龄是否大于或等于 18 岁且小于或等于 60 岁。如果条件为 TRUE,则该人可以申请工作。
- 如果条件为 FALSE,则根据政府规定,该人年龄过大,无法工作。
输出 1: 此处,年龄为 15 岁。第一个 If 条件为 TRUE,因此 If 语句内的语句显示为浏览器输出
JavaScript Else Statement
You are Minor.
Not Eligible to Work
第二个输出: 我们将年龄更改为 25。第一个 If 条件为 FALSE。嵌套 IF 条件为 TRUE。因此,嵌套 If 语句内的语句显示为浏览器输出

年龄 = 61。If 条件和嵌套 IF 条件在此处均失败。因此,嵌套 Else 语句内的语句显示为输出
You are too old to work as per the Government rules
Please Collect your pension!