프로그래머스 12939. 최댓값과 최솟값

slppills·2024년 7월 17일
0

TIL

목록 보기
28/69


처음 나의 코드

function solution(s) {
    return String(Math.min(s.split(' ').map(Number))) + " " + String(Math.max(s.split(' ').map(Number)));
}

이렇게 실행하니까 NaN이 나왔다.

찾아보니 Math.min과 Math.max 함수는 배열이 아니라 고유한 변수를 기대하기 때문에 배열에 Math.min과 Math.max를 쓰려면 spread가 필요하다.

JavaScript spread 연산자(...)를 사용하면 기존 배열이나 객체의 전체 또는 일부를 다른 배열이나 객체로 빠르게 복사할 수 있다.

최종 코드

function solution(s) {
    return String(Math.min(...s.split(' ').map(Number))) + " " + String(Math.max(...s.split(' ').map(Number)));
}

1개의 댓글

comment-user-thumbnail
2024년 7월 19일

답글 달기