Math.max()

Math.max() 静态方法返回作为输入参数给出的数字中的最大值,如果没有参数,则返回 -Infinity

¥The Math.max() static method returns the largest of the numbers given as input parameters, or -Infinity if there are no parameters.

Try it

语法

¥Syntax

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

参数

¥Parameters

value1, …, valueN

零个或多个数字,其中最大值将被选择并返回。

返回值

¥Return value

给定数字中最大的。如果任何参数已转换为 NaN,则返回 NaN。如果未提供参数,则返回 -Infinity

¥The largest of the given numbers. Returns NaN if any of the parameters is or is converted into NaN. Returns -Infinity if no parameters are provided.

描述

¥Description

因为 max()Math 的静态方法,所以你始终将其用作 Math.max(),而不是用作你创建的 Math 对象的方法(Math 不是构造函数)。

¥Because max() is a static method of Math, you always use it as Math.max(), rather than as a method of a Math object you created (Math is not a constructor).

Math.max.length 是 2,这微弱地表明它被设计为处理至少两个参数。

¥Math.max.length is 2, which weakly signals that it's designed to handle at least two parameters.

示例

¥Examples

使用 Math.max()

¥Using Math.max()

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

获取数组的最大元素

¥Getting the maximum element of an array

Array.prototype.reduce() 可用于通过比较每个值来查找数值数组中的最大元素:

¥Array.prototype.reduce() can be used to find the maximum element in a numeric array, by comparing each value:

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()。这只适用于元素相对较少的数组。

¥The following function uses Function.prototype.apply() to get the maximum of an array. getMaxOfArray([1, 2, 3]) is equivalent to Math.max(1, 2, 3), but you can use getMaxOfArray() on programmatically constructed arrays. This should only be used for arrays with relatively few elements.

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

扩展语法 是编写 apply 解决方案以获得数组最大值的更短方法:

¥The spread syntax is a shorter way of writing the apply solution to get the maximum of an array:

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

但是,如果数组元素过多,则 spread (...) 和 apply 都将失败或返回错误结果,因为它们尝试将数组元素作为函数参数传递。详细信息请参见 使用 apply 和内置函数reduce 解决方案不存在此问题。

¥However, both spread (...) and apply will either fail or return the wrong result if the array has too many elements, because they try to pass the array elements as function parameters. See Using apply and built-in functions for more details. The reduce solution does not have this problem.

规范

Specification
ECMAScript Language Specification
# sec-math.max

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看

¥See also