JavaScript 的 Math 是一个内置的全局对象,它拥有一些数学相关的常量属性和函数方法。Math 不是一个构造函数,因此我们不需要(也不能)使用 new Math() 来创建实例,所有的属性和方法都是静态的,直接通过 Math.xxx() 的形式调用。
Math 对象提供了一些常用的数学常量。
| 属性 | 描述 |
|---|---|
Math.E | 欧拉常数 e,自然对数的底数,约等于 2.718 |
Math.PI | 圆周率 π,约等于 3.14159 |
Math.SQRT2 | 2的平方根,约等于 1.414 |
Math.SQRT1_2 | 1/2的平方根,约等于 0.707 |
Math.LN2 | 2的自然对数,约等于 0.693 |
Math.LN10 | 10的自然对数,约等于 2.303 |
Math.round(x): 四舍五入到最接近的整数。
Math.round(4.7); // 5Math.round(4.4); // 4Math.round(4.5); // 5Math.ceil(x): 向上取整,返回大于或等于 x 的最小整数。
Math.ceil(4.7); // 5Math.ceil(4.4); // 5Math.ceil(-4.2); // -4Math.floor(x): 向下取整,返回小于或等于 x 的最大整数。
Math.floor(4.7); // 4Math.floor(4.4); // 4Math.floor(-4.2); // -5Math.trunc(x): 截断取整,直接去除小数部分,只保留整数部分。
Math.trunc(4.7); // 4Math.trunc(4.2); // 4Math.trunc(-4.2); // -4Math.max(...values): 返回一组数中的最大值。
Math.min(...values): 返回一组数中的最小值。
Math.max(1, 3, 2); // 3Math.min(1, 3, 2); // 1
// 可以配合展开语法 `...` 使用数组const numbers = [1, 3, 2, 8, -1];Math.max(...numbers); // 8Math.min(...numbers); // -1Math.pow(base, exponent): 返回 base 的 exponent 次幂,等同于 base ** exponent。
Math.pow(2, 3); // 8 (2 * 2 * 2)Math.sqrt(x): 返回 x 的正平方根。
Math.sqrt(16); // 4Math.abs(x): 返回 x 的绝对值。
Math.abs(-5); // 5Math.random(): 返回一个 [0, 1) 区间内的伪随机浮点数(包含0,不包含1)。
Math.random(); // 示例: 0.123456789生成指定范围的随机整数:
一个常见的需求是生成 [min, max] 区间内的随机整数。
function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min;}
getRandomInt(1, 10); // 返回 1 到 10 之间的一个随机整数Math 对象还提供了一整套三角函数,如 Math.sin(), Math.cos(), Math.tan() 等,参数为弧度制。