Javascript14(응용JS_조건문) feat.velopert

min seung moon·2021년 3월 6일
0

Javascript

목록 보기
17/23

1. 배열 이용

function isAnimal(text) {
    // 조건 중에 참이 있으면 true return, 없으면 false 리턴
    return text === '고양이' || text === '개' || text === '거북이' || text === '너구리'
}

console.log(isAnimal('개')); //true
console.log(isAnimal('노트북')); //flase

function isAnimal(text) {
    const animals = ['고양이', '개', '거북이', '너구리']
    // 배열 내장 메소드인 .include로 배열 안에 text 값이 있는지 확인
    return animal.include(text);
}

const isAnimal = (text) => ['고양이', '개', '거북이', '너구리'].include(text);

2. 객체 이용

function getSound(animal) {
    if (animal === '개') return '멍멍!'
    if (animal === '고양이') return '야옹~!'
    if (animal === '참새') return '짹짹!'
    if (animal === '비둘기') return '구구구구!'
    return '...?'
}

function getSound(animal) {
    switch(animal){
        case '개' :
            return '멍멍!'
        case '고양이' :
            return '야옹!'
        case '참새' :
            return '짹짹!'
        case '비둘기' :
            return '구구구구!'
        default :
            return '...?'
        
    }
}

console.log(getSound('개'));        // 멍멍!
console.log(getSound('비둘기'));    // 구구구구!
console.log(getSound('인간'));      // ...?

function getSound(animal) {
    const sounds = {
        개 : '멍멍',
        고양이 : '야옹',
        참새 : '짹짹',
        비둘기 : '구구구구'
    };

    return sounds[animal] || '...?';
}

function makeSound(animal) {
    const tasks = {
        개 : ()=>{
                console.log('멍멍');
            },
        고양이 : () {
                console.log('야옹')
            }
        참새 : function() {
                console.log('짹짹')
            }
        비둘기 : () {
                console.log('구구')
            }
    };

    const task = tasks[animal];

    if (!tasks[animal]) {
        console.log('...?');
        return;
    }

    task();
}
profile
아직까지는 코린이!

0개의 댓글