试一试
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 |
浏览器兼容性
加载中…