티스토리 뷰

요소가 숫자인 문자열을 배열로 반환한 후 max값을 구해봅시다.

 

 

 

처음 작성한 코드

const numbers = "10 11 5 6 12 7 3 9"
const arrNum = [...numbers];
const maxNum = Math.max(...numbers);

console.log (arrNum)   //9

max값이 12가 아닌 9가 반환된 이유는

컴퓨터는 문자열에 담긴 numbers가 숫자인지 모르니 ['10', '11', '5', ···] 가 아닌 ['1', '0', ' ', '1', '1', ' ', '5', ' ', '6', ' ', '1', ' ','2', ' ', '7', ' ', '3', ' ', '9'] 이런식으로 띄어쓰기를 포함한 각 요소들을 배열로 변환되었기 때문입니다.

이를 해결하기 위해서는 공백(띄어쓰기) 기준으로 split을 사용해 문자열을 자르면 됩니다.

 

 

 

완성 코드 (최댓값)

const numbers = "10 11 5 6 12 7 3 9"
const arrNum = numbers.split(" ");
const maxNum = Math.max(...arrNum);

console.log (maxNum)     //12

 

완성 코드 (최솟값)

const numbers = "10 11 5 6 12 7 3 9"
const arrNum = numbers.split(" ");
const maxNum = Math.min(...arrNum);

console.log (maxNum)   //3
Total
Today
Yesterday