JavaScript

Map, 배열의 최대 값(Max) 최소 값(Min) 구하기

cob 2022. 12. 17. 11:19

 

 

 

 

1. 기본 최대 값, 최소 값 구하기

파라미터 중 최대 값, 최소 값을 구한다.
const max = Math.max(1, 2, 3, 4, 5); 
console.log(max);
// 5

const min = Math.min(1, 2, 3, 4, 5);
console.log(min);
// 1

 

 

 

 


2. 배열의 최댓값 최소 값 구하기

2-1) Function.prototype.apply() 사용해 구하기

apply() 메서드는 주어진  this 값과 배열 (또는 유사 배열 객체)로 제공되는 arguments로 함수를 호출합니다.
const numbers = [5, 6, 2, 3, 7];
const max = Math.max.apply(null, numbers);

console.log(max);
// 7

const min = Math.min.apply(null, numbers);

console.log(min);
// 2
  • 따로 this객체를 지정해 줄 필요가 없으므로 null을 전달하였습니다.

 

 

2-2) […] 구조분해 할당을 사용해 구하기

const numbers = [5, 6, 2, 3, 7];

const max = Math.max(...numbers); // 7
const min = Math.min(...numbers); // 2

 

반응형