Math.max()함수는 입력값으로 받은 0개 이상의 숫자 중 가장 큰 숫자를 반환합니다.
문법
Math.max([값1[, 값2[, ...]]])
매개변수
값1, 값2, ...
- 숫자들.
반환 값
입력된 숫자 중 가장 큰 숫자를 반환합니다. 만약 인수 중 하나라도 숫자로 변환하지 못한다면 NaN
로 반환합니다.
설명
max ()는 Math의 정적 메서드이기 때문에 만든 Math 개체의 메서드가 아닌 항상 Math.max ()로 사용해야합니다. (Math는 생성자가 아닙니다).
만약 아무 요소도 주어지지 않았다면 -Infinity
로 반환합니다.
만약 한 개 이상의 요소가 숫자로 변환되지 않는다면 NaN
로 반환됩니다.
예제
Math.max()함수 사용하기
Math.max(10, 20); // 20
Math.max(-10, -20); // -10
Math.max(-10, 20); // 20
다음 함수는 Function.prototype.apply ()
을 사용하여 숫자 배열에서 최대 요소를 찾습니다. getMaxOfArray ([1, 2, 3])는 Math.max (1, 2, 3)와 동일하지만 프로그래밍 방식으로 생성 된 모든 크기의 배열에서 getMaxOfArray ()를 사용할 수 있습니다.
function getMaxOfArray(numArray) {
return Math.max.apply(null, numArray);
}
Array.reduce()
이 함수 또한 배열의 각 값을 비교하여 가장 큰 숫자를 얻을 수 있습니다.
var arr = [1,2,3];
var max = arr.reduce(function(a, b) {
return Math.max(a, b);
});
또한 spread operator
이 함수를 사용하면 배열의 숫자들 중 가장 큰 숫자를 쉽게 얻을 수 있습니다.
var arr = [1, 2, 3];
var max = Math.max(...arr);
표준
표준 | 상태 | 비고 |
---|---|---|
ECMAScript 1st Edition (ECMA-262) | Standard | Initial definition. Implemented in JavaScript 1.0. |
ECMAScript 5.1 (ECMA-262) The definition of 'Math.max' in that specification. |
Standard | |
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Math.max' in that specification. |
Standard | |
ECMAScript (ECMA-262) The definition of 'Math.max' in that specification. |
Living Standard |
브라우저 호환성
BCD tables only load in the browser
The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.