본문 바로가기
Java script

JavaScript_if문, 삼항 연산자, switch 조건문

by 디디찐 2022. 7. 31.
반응형

1. 조건문

if 문: 일반적으로 조건문 하나에 실행할 코드 작성시 사용한다.

//1. if문 기본 문법
if(조건문){

	만약 조건 (condition)이 참일 경우 실행할 코드

} 실행할 다른 코드 ;

//2. if,,,else 문
if (조건문){
	조건문이 참일 경우 실행할 코드
}else{ 
	거짓(false)일 경우 실행할 코드
}

//3. if,,else if문 ->여러가지의 조건문에 따라 실행할 코드를 작성할 때 사용
if (조건문1){
	조건문 1이 참일 경우 실행할 코드
}else if(조건문2){
	조건문 2이 참일 경우 실행할 코드
}else if(조건문3){
	조건문 3이 참일 경우 실행할 코드
}
,,,,,
else(모든 조건이 아닐 때){
}:

 

<if 문 예시>

<label for="theme">Select theme: </label>
<select id="theme">
  <option value="white">White</option>
  <option value="black">Black</option>
</select>

<h1>This is my website</h1>

const select = document.querySelector('select');
const html = document.querySelector('html');
document.body.style.padding = '10px';

function update(bgColor, textColor) {
  html.style.backgroundColor = bgColor;
  html.style.color = textColor;
}
-- if 조건문
select.onchange = function() {
  if(select.value =='black'){   // 선택한 값이 'black'일 때
  	update('black','white');
  }else{                 
  	update('white','black') // 선택한 값이 'black'이 아닐 때
  }
}

 

2. 삼항 연산자

삼항연산자는 if문을 한줄로 옮겨 작성할 수 있다

조건? true일 때 실행문: false 일 때 실행문

위의 if문을 삼항연산자로 바꿔쓰면 아래와 같이 작성할 수 있다.

( select.value === 'black' ) ? update('black','white') : update('white','black');

 

3. switch 조건문

switch(변수) 에 대해 case 의 상수와 같은지에 따라 실행문을 실행한다.

 

switch(변수){
	case 상수1 :  //변수 == 상수1일 때
   	     실행문1    //실행문 1 실행  
    	 break;
        
    case 상수2 :
    	 실행문
         break;
        
        ,,,
    default
    	 실행문
}

참고:   https://dasima.xyz/javascript-switch/

반응형