JavaScript 条件语句:if、else 和 else if

JavaScript 条件语句

JavaScript 中主要有三种类型的条件语句。

  1. if 语句:'if' 语句根据条件执行代码。
  2. if…else 语句:if…else 语句包含两个代码块;当条件为真时,它执行第一个代码块,当条件为假时,它执行第二个代码块。
  3. if…else if…else 语句:当需要测试多个条件并根据哪个条件为真来执行不同的代码块时,使用 if…else if…else 语句。

如何使用条件语句

条件语句用于根据不同条件决定执行流程。如果条件为真,您可以执行一个操作;如果条件为假,您可以执行另一个操作。

Use Conditional Statements in JavaScript

If 语句

语法

if(condition)
{
	lines of code to be executed if condition is true
}

如果您只想检查一个特定条件,可以使用 if 语句。

自己尝试一下

<html>
<head>
	<title>IF Statments!!!</title>
	<script type="text/javascript">
		var age = prompt("Please enter your age");
		if(age>=18)
		document.write("You are an adult <br />");
		if(age<18)
		document.write("You are NOT an adult <br />");
	</script>
</head>
<body>
</body>
</html>

If…Else 语句

语法

if(condition)
{
	lines of code to be executed if the condition is true
}
else
{
	lines of code to be executed if the condition is false
}

如果您需要检查两个条件并执行一组不同的代码,可以使用 If….Else 语句。

自己尝试一下

<html>
<head>
	<title>If...Else Statments!!!</title>
	<script type="text/javascript">
		// Get the current hours
		var hours = new Date().getHours();
		if(hours<12)
		document.write("Good Morning!!!<br />");
		else
		document.write("Good Afternoon!!!<br />");
	</script>
</head>
<body>
</body>
</html>

If…Else If…Else 语句

语法

if(condition1)
{
	lines of code to be executed if condition1 is true
}
else if(condition2)
{
	lines of code to be executed if condition2 is true
}
else
{
	lines of code to be executed if condition1 is false and condition2 is false
}

如果您想检查两个以上的条件,可以使用 If….Else If….Else 语句。

自己尝试一下

<html>
<head>
	<script type="text/javascript">
		var one = prompt("Enter the first number");
		var two = prompt("Enter the second number");
		one = parseInt(one);
		two = parseInt(two);
		if (one == two)
			document.write(one + " is equal to " + two + ".");
		else if (one<two)
			document.write(one + " is less than " + two + ".");
		else
			document.write(one + " is greater than " + two + ".");
	</script>
</head>
<body>
</body>
</html>