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
语法
参数
返回值
描述
¥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.
示例
使用 Math.max()
获取数组的最大元素
¥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:
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.
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:
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 |
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also