条件文 Javaスクリプト: if、else、else if
Javaスクリプト条件文
条件文には主に3つの種類があります。 Java脚本。
- ifステートメント: 「if」ステートメントは、条件に基づいてコードを実行します。
- if…elseステートメント: if…else ステートメントは XNUMX つのコード ブロックで構成されます。 条件が true の場合はコードの最初のブロックが実行され、条件が false の場合はコードの XNUMX 番目のブロックが実行されます。
- if…else if…else ステートメント: 複数の条件をテストする必要があり、どの条件が true であるかに基づいてコードの異なるブロックを実行する必要がある場合は、if…else if…else ステートメントが使用されます。
条件文の使用方法
条件ステートメントは、さまざまな条件に基づいて実行の流れを決定するために使用されます。 条件が true の場合は XNUMX つのアクションを実行でき、条件が false の場合は別のアクションを実行できます。
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 XNUMX つの条件をチェックし、別のコード セットを実行する必要がある場合は、ステートメントを使用します。
これを自分で試してみてください。
<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 XNUMX つ以上の条件を確認する場合は、ステートメントを使用します。
これを自分で試してみてください。
<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>

