반응형
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
실행문
}
반응형
'Java script' 카테고리의 다른 글
Javascript_이메일 형식 확인 정규식, 핸드폰 번호 형식 자동 적용 정규식 (0) | 2022.08.09 |
---|---|
JavaScript_두 INPUT 값 자동 합산 구현/ 숫자만 입력되도록 구현 하는 방법 (0) | 2022.08.08 |
JavaScript_자바스크립트 구성 요소, DOM접근 메소드 (0) | 2022.07.27 |
JavaScript_자바스크립트 개요, 기본 개념 (0) | 2022.07.27 |
JavaScript_자바스크립트 첫걸음/독학 방법 추천/ 사이트 추천 (0) | 2022.07.26 |