Math.max()

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨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 array = [1, 3, 2];

console.log(Math.max(...array));
// Expected output: 3

語法

js
Math.max()
Math.max(value1)
Math.max(value1, value2)
Math.max(value1, value2, /* …, */ valueN)

引數

value1, …, valueN

零個或多個數字,其中將選擇並返回最大的值。

返回值

給定的數字中的最大值。如果任何引數是或被轉換為 NaN,則返回 NaN。如果沒有提供引數,則返回 -Infinity

描述

因為 max()Math 的一個靜態方法,所以你總是使用 Math.max() 來呼叫它,而不是作為你建立的 Math 物件的某個方法(Math 不是一個建構函式)。

Math.max.length 的值為 2,這含蓄地表明它被設計為至少處理兩個引數。

示例

使用 Math.max()

js
Math.max(10, 20); // 20
Math.max(-10, -20); // -10
Math.max(-10, 20); // 20

獲取陣列中的最大元素

可以透過比較每個值來使用 Array.prototype.reduce() 來查詢數值陣列中的最大元素。

js
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()。這隻應用於元素相對較少的陣列。

js
function getMaxOfArray(numArray) {
  return Math.max.apply(null, numArray);
}

spread 語法(擴充套件語法)是編寫 apply 解決方案以獲取陣列中最大值的一種更簡潔的方法。

js
const arr = [1, 2, 3];
const max = Math.max(...arr);

然而,當陣列中的元素過多時,spread(...)和 apply 都會失敗或返回錯誤的結果,因為它們會嘗試將陣列元素作為函式引數傳遞。有關更多詳細資訊,請參閱 使用 apply 和內建函式reduce 解決方案沒有這個問題。

規範

規範
ECMAScript® 2026 語言規範
# sec-math.max

瀏覽器相容性

另見