条件语句 Java脚本:if、else、else if
Java脚本条件语句
条件语句主要有三种类型 Java脚本。
- if 语句:'if' 语句根据条件执行代码。
- if...else 语句:if…else 语句由两个代码块组成;当条件为真时,执行第一个代码块,当条件为假时,执行第二个代码块。
- if…else if…else 语句:当需要测试多个条件并且需要根据哪个条件为真执行不同的代码块时,使用 if...else if...else 语句。
如何使用条件语句
条件语句用于根据不同的条件决定执行流程。如果条件为真,则可以执行一个操作;如果条件为假,则可以执行另一个操作。
如果声明
语法:
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>

