JavaScript If Else 语句

JavaScript If Else 语句是我们在上一篇文章中已经解释过的 If 语句的扩展。它只在给定的表达式计算为 true 时执行代码。如果条件为 false,它将不会运行块内的任何代码。

在现实世界中,当条件失败时执行某些操作会很有用。为此,我们必须使用这个 If else 语句。在这里,Else 将在条件失败时执行语句。

JavaScript If Else 语句的语法如下:

if (Test condition)
{
  //If the condition is TRUE then these will be executed
  True statements;
}

else
{
  //If the condition is FALSE then these will be executed
  False statements;
}

如果在上述结构中测试条件为 true,则执行 True 语句。如果为 false,则执行 False 代码。

JavaScript If Else 语句示例

在这个 if else 示例程序中,我们将放置四个不同的语句。如果条件为 true,我们将显示两行不同的内容。如果条件为 false,JavaScript 将显示另外两行。请参阅 If condition 文章。

<!DOCTYPE html>

<html>
<head>
<title> Else Statement </title>
</head>
<h1> Else Statement </h1>
<body>
<script>
var marks = 60;
if( marks >= 50 )
{
document.write("<b> Congratulations </b>"); //s1
document.write("<br\> You Passed the subject" ); //s2
}
else
{
document.write("<b> You Failed </b>"); //s3
document.write("<br\> Better Luck Next Time" ); //s4
}
</script>
</body>
</html>

输出 1:这里 marks 为 60,条件为 TRUE,因此 If 语句内的语句显示为浏览器输出

If Else Statement 1

输出 2:这里,我们将 marks 变量更改为 30。这意味着条件为 FALSE,因此 Else 块内的代码显示为输出。

You Failed
Better Luck Next Time