javascript 기초정리 - 7_1

유경상·2022년 4월 27일
0

javascript

목록 보기
8/8

함수 문제

index.js meetAt 함수를 만들어주세요.
meetAt(2022); 결과 --> 2022년
meetAt(2032, 3); 결과 --> 2032년 3월
meetAt(1987, 10, 28); 결과 --> 1987년 10월 28일

숫자에 대한 매개변수를 넣었을 때, 결과가 나오게 하면 되는 문제이다.

문제풀이

function meetAt(year, month, date){
	console.log(year, month, date)
}

console.log(meetAt(2022))

로 출력을 하게 되면 2022 undefined undefined 가 나올 것이다.
매개변수 3가지 값을 넣어주어야 빈값을 채운다.

function meetAt(year, month, date){
	if(year){
    	return `${year}년`
    }else if(year && month){
    	return `${year}년 ${month}월`
    }else if(year && month && date){
    	return `${year}/${month}/${date}`
    }
}

console.log(meetAt(2022))
년도로만 출력하게 되면 "2022년"이 출력이 될 것이다.

여기서, console.log(meetAt(2022,1))로 월을 추가하게 되면
결과는 우선 "2022년"으로 나온다.
그러면 뒤에 나오는 월은 왜 안나올까?

위에 보게되면 if(year)에 보면 year에 포함을 하고 있기 때문에, year 정보가 있어서
다음 month정보가 나오지 않는다.

그렇다면, month가 나오게 하려면 순서를 바꾸어야한다.

function meetAt(year, month, date){
	if(year && month && date){
    	return `${year}/${month}/${date}`
    }else if(year && month){
    	return `${year}년 ${month}월`
    }else if(year){
    	return `${year}년`
    }
}


더 간편하게 쓰는방법은,


function meetAt(year, month, date){
	if(date){
    	return `${year}/${month}/${date}`
    }else if(month){
    	return `${year}년 ${month}월`
    }else if(year){
    	return `${year}년`
    }
}

month값이 같이 나오려면 year이 존재해야만 한다. 그래서 else if에 month만 적어두면 된다.
(month를 같이 출력할 때)

profile
하루하루

0개의 댓글