본문 바로가기
CS/알고리즘&자료구조

[코딩온] Math.min([array]) = NaN 해결 (JS)

by 새파란레몬 2023. 12. 12.

https://stackoverflow.com/questions/36608611/why-does-math-min1-2-return-nan

 

Why does Math.min([1,2]) return NaN?

I've been debugging this code for about an hour, and it looks like Math.min([1,2]) returns NaN. var int_array = [1,2] console.log(Math.min(int_array)) //prints NaN, but expect 1 isNaN(Math.min(int...

stackoverflow.com

 

최근에 코테를 준비중인데

 

그 중 array 내의 최댓값과 최솟값을 return 하는 Math.maxMath.min을 사용하려 했다.

하지만 Math.min([1,2]) 의 결과는 NaN이다.

 

왜냐하면 이 function은 숫자의 나열에 대해서 작동할 뿐,  array 를 직접적으로 인식하지 못하기 때문이었다.

 

console.log(Math.min(100, -2, 0, 5));

예를 들어 해당 콘솔의 값은 -2 이다.

 

따라서 array = [1,2] 라면

Math.min(...array)로 해결할 수 있다.

array = [1,2]
Math.min(...array)