Math.max()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. Itโs been available across browsers since โจ2015๋ 7์โฉ.
Math.max()
์ ์ ๋ฉ์๋๋ ๋งค๊ฐ๋ณ์๋ก ์ฃผ์ด์ง ์ซ์ ์ค ๊ฐ์ฅ ํฐ ์๋ฅผ ๋ฐํํ๊ฑฐ๋,
๋งค๊ฐ๋ณ์๊ฐ ์์ ๊ฒฝ์ฐ -Infinity
๋ฅผ ๋ฐํํฉ๋๋ค.
์๋ํด ๋ณด๊ธฐ
console.log(Math.max(1, 3, 2));
// Expected output: 3
console.log(Math.max(-1, -3, -2));
// Expected output: -1
const array1 = [1, 3, 2];
console.log(Math.max(...array1));
// Expected output: 3
๊ตฌ๋ฌธ
Math.max()
Math.max(value1)
Math.max(value1, value2)
Math.max(value1, value2, /* โฆ, */ valueN)
๋งค๊ฐ๋ณ์
value1
, โฆ,valueN
-
๊ฐ์ฅ ํฐ ๊ฐ์ ์ ํํ๊ณ ๋ฐํํ 0๊ฐ ์ด์์ ์ซ์์ ๋๋ค.
๋ฐํ ๊ฐ
์ฃผ์ด์ง ์ซ์ ์ค ๊ฐ์ฅ ํฐ ์ซ์๋ฅผ ๋ฐํํฉ๋๋ค. ๋ง์ฝ ์ธ์ ์ค ํ๋๋ผ๋ ์ซ์๋ก ๋ณํํ ๊ฐ์ด NaN
์ด๋ผ๋ฉด
NaN
๋ก ๋ฐํํฉ๋๋ค. ๋งค๊ฐ๋ณ์๊ฐ ์์ ๊ฒฝ์ฐ -Infinity
๋ฅผ ๋ฐํํฉ๋๋ค.
์ค๋ช
max()
๋ Math
์ ์ ์ ๋ฉ์๋์ด๊ธฐ ๋๋ฌธ์ ๋ง๋ Math
๊ฐ์ฒด์ ๋ฉ์๋๊ฐ ์๋ ํญ์
Math.max()
๋ก ์ฌ์ฉํด์ผํฉ๋๋ค. (Math๋ ์์ฑ์๊ฐ ์๋๋๋ค).
Math.max.length
์ ๊ฐ์ด 2 ์ธ๋ฐ, ์ด๋ ์ด ๋ฉ์๋๊ฐ ์ต์ 2๊ฐ์ ๋งค๊ฐ๋ณ์๋ฅผ ๋ฐ๋๋ก ์ค๊ณ๋์์์ ์์ํฉ๋๋ค.
์์
Math.max()ํจ์ ์ฌ์ฉํ๊ธฐ
Math.max(10, 20); // 20
Math.max(-10, -20); // -10
Math.max(-10, 20); // 20
๋ฐฐ์ด์ ์ต๋๊ฐ ๊ฐ์ ธ์ค๊ธฐ
Array.prototype.reduce()
๋ ๊ฐ ๊ฐ์ ๋น๊ตํ์ฌ ์ซ์ ๋ฐฐ์ด์ ์ต๋ ์์๋ฅผ ์ฐพ๋ ๋ฐ ์ฌ์ฉํ ์ ์์ต๋๋ค.
const arr = [1, 2, 3];
const max = arr.reduce((a, b) => Math.max(a, b), -Infinity);
๋ค์ ํจ์๋ Function.prototype.apply()
๋ฅผ ์ฌ์ฉํ์ฌ ๋ฐฐ์ด์ ์ต๋๊ฐ์ ๊ฐ์ ธ์ต๋๋ค. getMaxOfArray([1, 2, 3])
๋ Math.max(1, 2, 3)
์ ๋์ผํ์ง๋ง, ํ๋ก๊ทธ๋๋ฐ ๋ฐฉ์์ผ๋ก ๋ฐฐ์ด์ ์์ฑํ๊ธฐ ์ํด getMaxOfArray()
๋ฅผ ์ฌ์ฉํ ์ ์์ต๋๋ค. ์ด ํจ์๋ ์๋์ ์ผ๋ก ์์๊ฐ ์ ์ ๋ฐฐ์ด์๋ง ์ฌ์ฉํด์ผ ํฉ๋๋ค.
function getMaxOfArray(numArray) {
return Math.max.apply(null, numArray);
}
์ ๊ฐ ๊ตฌ๋ฌธ์ ๋ฐฐ์ด์ ์ต๋๊ฐ์ ๊ตฌํ๊ธฐ ์ํ apply
์๋ฃจ์
์ ์งง๊ฒ ์์ฑํ๋ ๋ฐฉ๋ฒ์
๋๋ค.
const arr = [1, 2, 3];
const max = Math.max(...arr);
๊ทธ๋ฌ๋ ์ ๊ฐ ๊ตฌ๋ฌธ(...
)์ apply
๋ ๋ชจ๋ ๋ฐฐ์ด ์์๋ฅผ ํจ์ ๋งค๊ฐ๋ณ์๋ก ์ ๋ฌํ๋ ค๊ณ ํ๊ธฐ ๋๋ฌธ์ ๋ฐฐ์ด์ ์์๊ฐ ๋๋ฌด ๋ง์ผ๋ฉด ์คํจํ๊ฑฐ๋
์๋ชป๋ ๊ฒฐ๊ณผ๋ฅผ ๋ฐํํฉ๋๋ค. ์์ธํ ๋ด์ฉ์ apply์ ๋ด์ฅ ํจ์ ์ฌ์ฉํ๊ธฐ๋ฅผ ์ฐธ์กฐํ์ธ์.
reduce
์๋ฃจ์
์๋ ์ด ๋ฌธ์ ๊ฐ ์์ต๋๋ค.
๋ช ์ธ์
Specification |
---|
ECMAScriptยฎ 2026 Language Specification # sec-math.max |
๋ธ๋ผ์ฐ์ ํธํ์ฑ
Loadingโฆ