Math.max()
1
2
3
4
5
6
7
8
9
10
11
|
console.log(Math.max(1, 3, 2));
// expected output: 3
console.log(Math.max(-1, -3, -2));
// expected output: -1
var array1 = [1, 3, 2];
console.log(Math.max(...array1));
// expected output: 3
|
cs |
Math.min()
1
2
3
4
5
6
7
8
9
10
11
|
console.log(Math.min(2, 3, 1));
// expected output: 1
console.log(Math.min(-2, -3, -1));
// expected output: -3
var array1 = [2, 3, 1];
console.log(Math.min(...array1)); // 배열일 경우 ...을 붙이는거 같다.
// expected output: 1
|
cs |
3개의 변수 중 최대값/최소값을 구하려고 할때
간단하게 Math.max() 또는 Math.min() 함수를 사용하여 최대값과 최소값을 구할 수 있습니다.
1
2
3
|
let x = 10, y = 20, z = 30;
Math.max(x, y, z); // ---> 30
Math.min(x, y, z); // ---> 10
|
cs |
숫자 배열에서 최대값/최소값을 구하려고 할때
for문을 돌면서 가장 큰수 또는 작은수를 비교하면서 구하는 방법 등 여러가지 방법이 있습니다.
하지만, 배열의 길이가 길어질수록 퍼포먼스는 떨어지게 되고 불필요한 변수를 만들어야 하는 단점이 있습니다.
Function.prototype.apply(), Array.reduce(), spread operator 를 사용하면 간단하게 해결할 수 있습니다.
(spread operator의 경우 ES2015에서 추가된 기능으로 지원하는 브라우저를 고려하여 사용해야 합니다.)
· Function.prototype.apply()
1
2
3
|
let arr = [1, 4, 2, 7, 8, 3];
Math.max.apply(null, arr); // return 8
Math.min.apply(null, arr); // return 1
|
cs |
(1) apply를 붙여야하는 이유?
(2) null값을 넣은 이유?
Math.max.apply(null, [6,4,7,2,3,4,10]) 은 결과적으로 Math.max(6,4,7,2,3,4,10) 이 됩니다.
apply() 메서드는 함수 객체의 메서드인데 두 번째 인자의 값으로 어레이를 받아 각 어레이의 요소를 함수의 인자로 전부 넘겨줍니다.
첫 번째 인수는 해당 함수 내의 this에 연결되는 값으로 만약 this가 상관없는 함수라면 별 의미가 없기 때문에 null이나 undifined를 넣어 주는 것 같습니다.
만약 Math.max 메서드에 인자로 이렇게 어레이를 넘겨 주면 제대로 작동하지 않습니다.
1
2
3
|
Math.max([6,4,7,2,3,4,10]) // -> NaN
|
cs |
MDN 문서라면 Function.prototype.apply() 항목을 보셨겠군요.
MDN: Function.prototype.call() 도 보시는 것을 추천드립니다.
두 메서드의 차이는 call은 두 번째 인자부터 그냥 그대로 함수의 인자로 넘겨 주는 데에 반해, apply는 두 번째 인자가 어레이라는 차이만 있는 것 같습니다.
· Array.reduce()
1
2
3
4
5
6
7
8
|
let arr = [1, 4, 2, 7, 8, 3];
arr.reduce((a,b) => {
return Math.max(a, b);
}); // return 8
arr.reduce((a, b) => {
return Math.min(a, b);
}); // return 1
|
cs |
· spread operator
1
2
3
|
let arr = [1, 4, 2, 7, 8, 3];
Math.max(...arr); // return 8
Math.min(...arr); // return 1
|
cs |
참조
MDN, https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Math/max
MDN, https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
'Programing > JavaScript' 카테고리의 다른 글
[JavaScript] Object Length 구하기 (0) | 2019.01.26 |
---|---|
[JavaScript] Array.prototype.sort() (0) | 2019.01.25 |
[JavaScript] 생성자와 new // + this 조금 // 객체 (0) | 2019.01.25 |
Array.prototype.unshift() // 배열의 맨앞에 요소추가 (0) | 2019.01.24 |
typeof, Number.isInteger(), isFinite(), isNaN() // 데이터 유형찾기 (0) | 2019.01.24 |