조건문을 더 간결하고 효율적으로 작성할 수 있는 방법 중 가장 기본적인 두 가지 방법을 알아보겠습니다.
① 배열 내장함수 includes 이용
조건문의 조건식이 여러가지 케이스 중 하나에 해당하는지를 비교하는 경우일 때 배열 내장함수 includes를 이용하는 방법입니다.
[예시 코드]
/* 태극기에 사용되는 색상인지를 검사 */
function isTaegeukgiColor(color) {
if (
color == "white" ||
color == "black" ||
color == "red" ||
color == "blue"
) {
return true;
}
return false;
}
const color1 = isTaegeukgiColor("red");
const color2 = isTaegeukgiColor("yellow");
console.log(color1); //true
console.log(color2); //flase
⇓
/* 태극기에 사용되는 색상인지를 검사 */
const taegeukgiColor = ["white", "black", "red", "blue"];
function isTaegeukgiColor(color) {
if (taegeukgiColor.includes(color)) {
return true;
}
return false;
}
const color1 = isTaegeukgiColor("red");
const color2 = isTaegeukgiColor("yellow");
console.log(color1); //true
console.log(color2); //false
② 객체의 괄호 표기법
조건문의 return 값이 여러 개 중 하나가 되는 경우에 객체의 프로퍼티에 접근하는 괄호 표기법을 이용하는 방법입니다.
[예시 코드]
/* 태극기의 어떤 부분에 이용되는 색상인지를 검사 */
const whichPart = (color) => {
if (color === "white") return "바탕";
if (color === "black") return "건곤감리";
if (color === "red" || color === "blue") return "태극 문양";
return "* 태극기에 사용되는 색상이 아닙니다.";
};
console.log(whichPart("black")); //건곤감리
console.log(whichPart("red")); //태극 문양
console.log(whichPart("yellow")); //* 태극기에 사용되는 색상이 아닙니다.
⇓
/* 태극기의 어떤 부분에 이용되는 색상인지를 검사 */
const Taegeukgi = {
white: "바탕",
black: "건곤감리",
red: "태극 문양",
blue: "태극 문양"
};
const whichPart = (color) => {
return Taegeukgi[color] || "* 태극기에 사용되는 색상이 아닙니다. ";
};
console.log(whichPart("black")); //건곤감리
console.log(whichPart("red")); //태극 문양
console.log(whichPart("yellow")); //* 태극기에 사용되는 색상이 아닙니다.
'웹 > JavaScript' 카테고리의 다른 글
[JS] 문서 객체 모델(DOM) 1 - DOM이란? / document 객체와 관련 메소드 (0) | 2022.10.27 |
---|---|
[JS] 16. 응용: 비 구조화 할당 / spread 연산자 (0) | 2022.07.20 |
[JS] 14. 응용: Truthy & Falsy / 삼항 연산자 / 단락 회로 평가 (0) | 2022.07.18 |
[JS] 13. 기초 문법: 배열 내장함수 (0) | 2022.07.17 |
[JS] 12. 기초 문법: 반복문 (for문) (0) | 2022.07.16 |