Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

JavaScript의 조건문

<시간/>

JavaScript에는 세 가지 유형의 조건문이 있습니다 -

  • If 문 − if 문은 특정 조건이 충족되는 경우에만 if 블록 내부의 코드를 실행하는 데 사용됩니다.
  • If else 문 − If….Else 문은 두 가지 조건만 확인하고 각각에 대해 다른 코드를 실행하는 데 사용됩니다.
  • If else if else 문 − if…else if…else 문은 두 개 이상의 조건을 확인하는 데 사용됩니다.

다음은 JavaScript에서 조건문을 구현하는 코드입니다 -

예시

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 20px;
      font-weight: 500;
      color: blueviolet;
   }
</style>
</head>
<body>
<h1>Conditional statements in JavaScript</h1>
<input type="text" class="numInput" />
<button class="Btn">CHECK</button><br />
<div class="result"></div>
<h3>Click on the above button to see if the above number is divisible by 2,3 or both</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   let numInputEle = document.querySelector(".numInput");
   BtnEle.addEventListener("click", () => {
      if (numInputEle.value % 2 === 0 && numInputEle.value % 3 === 0) {
         resEle.innerHTML = "The numbers is divisible by 2 and 3 both";
      } else if (numInputEle.value % 3 === 0) {
         resEle.innerHTML = "The number is divisbly by 3";
      } else if (numInputEle.value % 2 === 0) {
         resEle.innerHTML = "The numbers is divisible by 2";
      } else {
         resEle.innerHTML = "The numbers isn't divisible by 2 or 3";
      }
   });
</script>
</body>
</html>

출력

JavaScript의 조건문

숫자를 입력하고 'CHECK' 버튼을 클릭하면 -

JavaScript의 조건문