learnjs
learnjs copied to clipboard
05. 조건문 더 스마트하게 쓰기 · GitBook
마지막 예제에서 getSound
가 아니라 makeSound
함수를 호출해야할 것 같습니다 :smile:
getSound 와 makeSound 함수에는 어떤 차이가 있을까요?
@saewookkangboy getSound 는 소리를 받아와서 직접 출력합니다. makeSound 는 함수가 출력을 합니다.
^^ 심심해서 적어봐요.
// 값에 따른 결과물 반환
function getSound(animal) { if(animal === '개') return '멍멍!' if(animal === '고양이') return '야옹' if(animal === '참새') return '짹짹' if(animal === '비둘기') return '구구' return '...?' }
console.log(getSound('개')) console.log(getSound('비둘기')) // 출력 : 멍멍! 구구
// switch문 사용 function getSound(animal){ switch(animal) { case '개': return '멍멍!' case '고양이': return '야옹' case '참새': return '짹짹' case '비둘기': return '구구' default: return '...?' } } console.log(getSound('개')) console.log(getSound('비둘기')) // 출력 : 멍멍! 구구
// 배열의 다른 방법 function getSound(animal){ const sounds = { 개: '멍멍!', 고양이: '야옹', 참새: '짹짹', 비둘기: '구구' } return sounds[animal] || '...?' } console.log(getSound('개')) console.log(getSound('비둘기')) // 출력 : 멍멍! 구구
// 객체의 다른 방법 function makeSound(animal) { const tasks = { 개() { return '멍멍' }, 고양이() { return '고양이' }, 비둘기() { return '구구' } } if(!tasks[animal]) { return '...?' } return tasksanimal } console.log(makeSound('개')) console.log(makeSound('비둘기')) console.log(makeSound('염소')) // 출력 : 멍멍 구구 ...?
creativeahn님 tasks[animal]은 tasks안에 있는 요소들중에 animal과 같은 이름의 메소드를 의미하는것이고, 함수표현식이라서 가능한겁니당
22.03.22
22.03.25
22.05.24
수강 완료
22.08.18
230202
240624