티스토리 뷰
Conditions (조건문)
🙾 컴퓨터는 2진수 1은 true, 0은 flase로 출력
ex)
1 ➡ true
0 ➡ flase
1 == 1 ➡ true
1 == 0 ➡ false
🙾 ! (반대)
ex)
!true ➡ false
!false ➡ true
1 !== '1' ➡ true (1과 문자 '1'이 다르냐고 묻는 것 )
🙾 == 숫자, ===는 데이터 타입
ex)
1 == '1' ➡ true
1 === '1' ➡ false
<script>
/*
if(조건){
참일 때 할일
} else{
거짓일 때 할일
}
*/
var a = 10;
var b = 20;
if(a>b){
document.write('a가 b보다 크다');
} else{
document.write('a가 b보다 작다');
}
</script>
<script>
var aa = 30;
var bb = 30;
if(aa>bb){
document.write('a가 b보다 크다');
} else if(aa !== bb){
document.write('a가 b보다 작다');
} else {
document.write('a와 b는 같다');
}
</script>
▏비교연산자 (★)

▏타입 비교
① != , == : 숫자인지 문자인지 구분하지 않음
② !==, === : 숫자인지 문자인지 타입까지 비교
<script>
if(1 != '1'){
document.write('두 값은 다르다');
} else{
document.write('두 값은 같다');
}
if(1 !== '1'){
document.write('두 값은 다르다');
} else{
document.write('두 값은 같다');
}
</script>
▏중첩 조건문
- 조건문 안에 조건문
<script>
a = 10;
b = 20;
if(a != b){
if(a>b){
document.write('a가 크다');
}else{
document.write('b가 크다');
}
} else {
document.write('두 값은 같다');
}
</script>
▏조건문의 축약
<script>
if(a>b){
document.write('a가 크다');
}else{
document.write('b가 크다');
}
// 중괄호를 삭제(=생략)
if(a>b) document.write('a가 크다');
else document.write('b가 크다');
// if, else 삭제
(a>b) ? document.write('a가 크다') : document.write('b가 크다');
// (a>b) ? document.write('a가 크다'); 불가
// 거짓일 때 할 일이 있는 조건문만 축약가능
// 반드시 else가 뒤따라야 함
</script>
▏논리연산자
① A && B : A조건과 B조건 모두 참일 때 참
② A || B : A조건과 B조건 둘 중 하나라도 참일 때 참
= 둘 다 참이여도 하나가 참이기 때문에 결과는 참
<script>
var a = 10;
var b = 20;
var c = 30;
// A && B : A조건과 B조건 모두 참일 때는 참이다
if(a<b && b<c){
document.write('a는 b보다 작고, b는 c보다 작다');
}
// A || B : A조건과 B조건 둘 중 하나라도 참일 때는 참이다
if(a<b || b==c){
document.write('a는 b보다 작고, b는 c보다 작다');
}
</script>
▏switch
- 어떤 값을 가진 대상을 두고 조건값과 일치하는 지를 확인하고 동작을 수행하는 방식
/* <pre>
swich(조건){
case 1:
할일;
break;
case 2:
할일;
break;
case 3:
할일;
break;
default:
할일;
break;
}
</pre> */
<script>
var number = prompt('숫자를 입력하세요', '0');
console.log(number);
switch(number % 2){
case 0: alert ('짝수');
break;
case 1: alert ('홀수');
break;
default: alert ('숫자가 아닙니다');
break;
}
</script>
'JavaScript' 카테고리의 다른 글
| Timer & Math (0) | 2023.06.05 |
|---|---|
| 문자열 (IndexOf, Search / concat / replace / slice / split / length) (0) | 2023.06.05 |
| 반복문 (for / while / do while / forEach / for in / for of ) (0) | 2023.06.05 |
| Object(객체) / Array(배열) (0) | 2023.06.02 |
| Javascript? / variant(변수) / function(함수) / Atrribute(속성) (0) | 2023.06.01 |
