조건문 Java스크립트: if, else, else if
Java스크립트 조건문
조건문에는 크게 세 가지 유형이 있습니다. Java스크립트.
- if 문: 'if' 문은 조건에 따라 코드를 실행합니다.
- if…else 문: if…else 문은 두 개의 코드 블록으로 구성됩니다. 조건이 true이면 첫 번째 코드 블록을 실행하고, 조건이 false이면 두 번째 코드 블록을 실행합니다.
- if…else if…else 문: 여러 조건을 테스트해야 하고 어떤 조건이 참인지에 따라 다양한 코드 블록을 실행해야 하는 경우 if…else if…else 문이 사용됩니다.
조건문을 사용하는 방법
조건문은 다양한 조건에 따라 실행 흐름을 결정하는 데 사용됩니다. 조건이 true이면 한 가지 작업을 수행할 수 있고, 조건이 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 두 가지 조건을 확인하고 다른 코드 세트를 실행해야 하는 경우 명령문입니다.
직접 시도해 보세요.
<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>

