switch 문
기본적으로 여러 다른 옵션에 우리가 원하는 모든 것이 하나의 값을 비교하는 것일때 작성하기 복잡한 if else문을 대체할 수 있는 방법은 switch문이다.
월, 화, 수, 목, 금, 토, 일을 나타내기 위해 if else문을 사용할 수 있지만 더욱 쉽게 switch문을 사용할 수 있다. 내가 지금 전환하려고 하는 것은 요일이다.
일단 먼저 switch () 를 작성하고 블록을 정의하기 위해 { } 중괄호를 사용한다. 그 다음 case를 정의한다.
switch (day) {
case "monday": ← 이때! 세미콜론이 아니라 콜론 : 으로 작성해야 한다.
}
이제 여러 줄을 작성하려면 중괄호는 필요하지 않다. (마무리 할때 필요하다.)
const day = "monday";
switch (day) {
case "monday": //day === ' monday'
console.log("Pan course structure");
console.log("Go to meetup");
}
이렇게 작성한뒤 break문이 필요하다.
const day = "monday";
switch (day) {
case "monday": //day === ' monday'
console.log("Pan course structure");
console.log("Go to meetup");
break;
}
그 다음 위의 코드를 반복적으로 화, 수, 목, 금, 토, 일을 추가하면 된다.
만일 두개의 다른 값에 대해 동일한 코드를 실행시키려면
case "wensday":
case "thursay": ← 이런 식으로 작성하면 된다.
따라서 if else문에 필요한거처럼 논리 연산자가 필요 없다.
const day = "monday";
switch (day) {
case "monday": //day === ' monday'
console.log("Pan course structure");
console.log("Go to meetup");
break;
case " tuesday":
console.log("Prepare theory videos");
break;
case "wensday":
case "thursay":
console.log("Write code exmpels");
break;
case "friday":
console.log("Record videos");
break;
case "saturday":
case "sunday":
console.log("Enjoy the weekend :D");
break;
}
day === 'monday' 이므로 Pan course structure 과 Go to meetup 두 문장이 실행되었다.
만일 다른 모든 경우가 실패하면 default:를 작성한다.
break;를 작헝하는 이유는 각 블록이후에 중지하라는 의미이다.
만일 break;가 없으면 다음 값도 실행될것이다.
switch문은 엄격하게 비교한다.
if else문을 이용하려면 논리 연산자를 이용해야한다.
const day = "monday";
if (day === "monday") {
console.log("Pan course structure");
console.log("Go to meetup");
} else if (day === "tuesday") {
console.log("Prepare theory videos");
} else if (day === "wensday" || day === "thursday") {
console.log("Write code exmpels");
} else if (day === "friday") {
console.log("Record videos");
} else if (day === "saturday" || day === "sunday") {
console.log("Enjoy the weekend :D");
} else {
console.log("Not a valid day!");
}
switch 문과 같은 결과가 나왔다.
'🦎 JavaScript' 카테고리의 다른 글
[JS] JS가 작동하는 방식 (0) | 2023.02.02 |
---|---|
[JS] 조건(삼항) 연산자 (0) | 2023.02.02 |
[JS] Boolean logic | Logical Operators (0) | 2023.01.31 |
[JS] 비교 연산자(Equality Operators) (0) | 2023.01.31 |
[JS] 형 변환과 타입 강제 변환 (0) | 2023.01.30 |