프론트엔드 (Front-End)/자바스크립트 ( Javascript )

<Javascript> 다중으로 조건문 연산하기 (삼항연산자)

xxvigrufv 2023. 11. 6. 19:54
반응형

다중연산자는 모두가 알고 있다. 
그럼 3개 이상은 어떻게 구현해야 할까,,?

 

- 구문 

condition ? exprIfTrue : exprIfFalse

 

< 다중으로 연결된 조건문 처리하기 >

 

조건 연산자는 아래와 같이 연결해 사용할 수 있다.

이는 연결된 if … else if … else if … else와 유사합니다.

 

function example(…) {
    return condition1 ? value1
         : condition2 ? value2
         : condition3 ? value3
         : value4;
}

 

위 코드는 아래의 연결된 if ...else 문과 동일하다고 볼 수 있다.

function example(…) {
    if (condition1) { return value1; }
    else if (condition2) { return value2; }
    else if (condition3) { return value3; }
    else { return value4; }
}

type: el.conditionType == "TIME" ? this.$t("ztca.condition.timeTitle") : el.conditionType === "IP_ADDRESS" ? this.$t("ztca.condition.locationTitle") : el.conditionType === "STRING" ? this.$t("위치(국가)") : this.$t("미정");

 

 

<NULL 값 처리하기>
NULL일 수 있는 값을 처리할 때 흔히 사용한다:

 

let greeting = person => {
  let name = person ? person.name : `stranger`
  return `hello, ${name}`
}

console.log(greeting({name: `Alice`}));  // "hello, Alice"
console.log(greeting(null));             // "hello, stranger"

 

반응형