[JS_오답노트]_IF문 예제2

hanseungjune·2022년 5월 29일
0

JavaScript

목록 보기
16/87

문제

코드

// 나의 나이와, 나의 성별을 저장하는 변수
let myAge = 26;
let myGender = 'male';

// 호칭을 담은 변수
let callOlderBrother = '형';
let callOlderSister = '누나';
let callFriend = '친구';
let callYoungerSister = '여동생';
let callYoungerBrother = '남동생';

// 상대방의 나이와 성별에 따른 호칭을 리턴하는 함수 whatShouldICall를 완성하세요.
function whatShouldICallYou(yourAge, yourGender) {
  // 여기에 코드를 작성해 주세요.
  if( myAge === yourAge ){
    return callFriend;
  }
  else if( myAge > yourAge){
    if( yourGender === 'male') {
      return callYoungerBrother;
    }
    else {
      return callYoungerSister;
    }
  }
  else{
    if( yourGender === 'male') {
      return callOlderBrother;
    }
    else {
      return callOlderSister;
    }
  }
}

// 테스트 코드
let result1 = whatShouldICallYou(25, 'female');
let result2 = whatShouldICallYou(20, 'male');
let result3 = whatShouldICallYou(26, 'female');
let result4 = whatShouldICallYou(30, 'male');
let result5 = whatShouldICallYou(31, 'female');

console.log(result1);
console.log(result2);
console.log(result3);
console.log(result4);
console.log(result5);

풀이

IF문을 사용하여 문제를 풀었는데, 하나 아쉬운 부분이 있다.

가급적 조건문 내부에 또 조건문을 쓰는 걸 피하라고 들었는데, 그러지 못해서 아쉽다.

(여동생, 남동생) 구분과 (형, 누나) 구분을 할 때 else if 안에 if 를 사용했다는 애기

다음에 작성한다면,
if ( myAge > yourAge && yourGender === 'male' ) { 남동생 }
else if ( myAge > yourAge && yourGender === 'female' ) { 여동생 }
else if ( myAge < yourAge && yourGender === 'male' ) { 형 }
else if ( myAge < yourAge && yourGender === 'female' ) { 누나 }
else { 동갑 }

이렇게 작성할듯!

profile
필요하다면 공부하는 개발자, 한승준

0개의 댓글