Math.min()

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

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

Try it

语法

¥Syntax

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

参数

¥Parameters

value1, …, valueN

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

返回值

¥Return value

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

¥The smallest 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

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

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

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

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

示例

¥Examples

使用 Math.min()

¥Using Math.min()

找到 xy 的最小值并将其分配给 z

¥This finds the min of x and y and assigns it to z:

js
const x = 10;
const y = -20;
const z = Math.min(x, y); // -20

使用 Math.min() 剪切值

¥Clipping a value with Math.min()

Math.min() 通常用于裁剪一个值,使其始终小于或等于边界。例如,这个

¥Math.min() is often used to clip a value so that it is always less than or equal to a boundary. For instance, this

js
let x = f(foo);

if (x > boundary) {
  x = boundary;
}

可以写成这样

¥may be written as this

js
const x = Math.min(f(foo), boundary);

Math.max() 可以以类似的方式使用来剪辑另一端的值。

¥Math.max() can be used in a similar way to clip a value at the other end.

规范

Specification
ECMAScript Language Specification
# sec-math.min

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看

¥See also