JavaScript Tutorial.37

ansunny1170·2021년 12월 27일
0
post-thumbnail

JS if else and else if

조건문은 다른 조건에 따라 다른 작업을 수행하는 데 사용된다.

Conditional Statements

코드를 작성할 때 서로 다른 결정에 대해 서로 다른 작업을 수행하려는 경우가 많다.
이를 위해 코드에서 조건문을 사용할 수 있다.
JavaScript에는 다음과 같은 조건문이 있다.

  • 지정된 조건이 true인 경우 실행할 코드 블록을 지정하려면 if를 사용한다.
  • 동일한 조건이 false인 경우 else를 사용하여 실행할 코드 블록을 지정한다.
  • 첫 번째 조건이 false인 경우 테스트할 새 조건을 지정하려면 else if를 사용한다.
  • 실행할 많은 대체 코드 블록을 지정하려면 switch를 사용한다.

    switch 문은 다음 장에서 배우자.

The if Statement

if 문을 사용하여 조건이 true인 경우 실행할 JavaScript 코드 블록을 지정한다.
Syntax

if (condition) {
  //  block of code to be executed if the condition is true
}

if 는 소문자다. 대문자(If 또는 IF)는 JavaScript 오류를 생성한다.

The else if Statement

첫 번째 조건이 false인 경우 else if 문을 사용하여 새 조건을 지정한다.
Syntax

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

More Examples

아래 예시에서는 W3Schools 또는 WWF(세계 야생 동물 재단)에 대한 링크를 연결시킨다. 난수를 사용하면 각 링크에 대해 50%의 확률이 있다.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math.random()</h2>

<p id="demo"></p>

<script>
let text;
if (Math.random() < 0.5) {
  text = "<a href='https://w3schools.com'>Visit W3Schools</a>";
} else {
  text = "<a href='https://wwf.org'>Visit WWF</a>";
}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

profile
공정 설비 개발/연구원에서 웹 서비스 개발자로 경력 이전하였습니다. Node.js 백엔드 기반 풀스택 개발자를 목표로 하고 있습니다.

0개의 댓글