网站
引入
做数学计算时,不可能所有公式都自己写。
比如取整、求随机数、算平方根、比较大小,JS 已经内置了 Math 对象,直接调用它的方法就行。
正文
定义
定义
Math是 JS 内置的数学对象,提供了常用的数学计算方法和数学常量。它不是构造函数,不需要也不能用new创建。
基本使用
Math 的所有方法和属性都是静态的,直接用 Math.xxx() 调用。
console.log(Math.PI);
console.log(Math.round(3.5));
console.log(Math.random());不能用 new Math(),会报错。
取整方法
Math.round()
四舍五入到最接近的整数。
console.log(Math.round(3.4));
console.log(Math.round(3.5));
console.log(Math.round(3.6));
console.log(Math.round(-3.5));注意:Math.round(-3.5) 结果是 -3,向正数方向取整。
Math.floor()
向下取整(取比它小或相等的最大整数)。
console.log(Math.floor(3.9));
console.log(Math.floor(3.1));
console.log(Math.floor(-3.1));Math.ceil()
向上取整(取比它大或相等的最大整数)。
console.log(Math.ceil(3.1));
console.log(Math.ceil(3.9));
console.log(Math.ceil(-3.9));Math.trunc()
直接去掉小数部分,只保留整数。
console.log(Math.trunc(3.9));
console.log(Math.trunc(-3.9));
console.log(Math.trunc(3.1));取整方法对比
| 方法 | 3.7 | -3.7 | 说明 |
|---|---|---|---|
Math.round() | 4 | -4 | 四舍五入 |
Math.floor() | 3 | -4 | 向下取整 |
Math.ceil() | 4 | -3 | 向上取整 |
Math.trunc() | 3 | -3 | 截断小数 |
随机数
Math.random()
返回一个 0(包含)到 1(不包含)之间的随机小数。
console.log(Math.random());每次调用结果都不一样。
常用随机数模式
生成 0 到 max 之间的随机整数(不包含 max):
let max = 10;
console.log(Math.floor(Math.random() * max));生成 min 到 max 之间的随机整数(包含 min,不包含 max):
let min = 5;
let max = 10;
console.log(Math.floor(Math.random() * (max - min)) + min);生成 min 到 max 之间的随机整数(包含两端):
let min = 1;
let max = 6;
console.log(Math.floor(Math.random() * (max - min + 1)) + min);比较大小
Math.max()
返回参数中的最大值。
console.log(Math.max(1, 3, 5, 2));Math.min()
返回参数中的最小值。
console.log(Math.min(1, 3, 5, 2));配合数组使用
Math.max() 和 Math.min() 不能直接传数组,需要用展开语法。
let list = [3, 1, 4, 1, 5];
console.log(Math.max(...list));
console.log(Math.min(...list));绝对值
Math.abs()
返回一个数的绝对值。
console.log(Math.abs(-5));
console.log(Math.abs(5));
console.log(Math.abs(0));幂和平方根
Math.pow()
计算幂,Math.pow(x, y) 表示 x 的 y 次方。
console.log(Math.pow(2, 3));
console.log(Math.pow(5, 2));ES6 也可以用 ** 运算符代替。
console.log(2 ** 3);Math.sqrt()
计算平方根。
console.log(Math.sqrt(9));
console.log(Math.sqrt(2));数学常量
| 常量 | 值(约) | 说明 |
|---|---|---|
Math.PI | 3.14159 | 圆周率 |
Math.E | 2.71828 | 自然对数的底数 |
Math.LN2 | 0.69314 | 2 的自然对数 |
Math.LN10 | 2.30258 | 10 的自然对数 |
Math.SQRT2 | 1.41421 | 2 的平方根 |
实际最常用的是 Math.PI。
let radius = 5;
let area = Math.PI * radius ** 2;
console.log(area);常见写法
| 写法 | 作用 |
|---|---|
Math.round(n) | 四舍五入 |
Math.floor(n) | 向下取整 |
Math.ceil(n) | 向上取整 |
Math.trunc(n) | 截断小数 |
Math.random() | 生成 0~1 随机数 |
Math.max(a, b, c) | 取最大值 |
Math.min(a, b, c) | 取最小值 |
Math.abs(n) | 取绝对值 |
Math.pow(x, y) | x 的 y 次方 |
Math.sqrt(n) | 平方根 |
Math.PI | 圆周率 |
特点
Math是内置对象,不需要new,也不能new- 所有方法都是静态方法,用
Math.xxx()调用 - 取整方法有四种,区别在于正负数的处理
Math.random()生成 0 到 1 之间的随机数,常用Math.floor配合取随机整数Math.max()和Math.min()要配合展开语法才能处理数组
理解
Math 对象可以理解为一个数学计算器。
取整、随机数、求幂、开方这些操作,不需要自己写公式,Math 都已经帮你写好了。
日常最常用的就三个:Math.random()(随机数)、Math.floor()(向下取整)、Math.round()(四舍五入)。
特别是随机数,抽奖、随机排序、随机颜色这些功能都要用到它。
引出
Math 主要处理数字运算,关于数字类型本身的判断和转换,可以看 JS Number 对象。
关于数字的基础知识,可以回顾 JS 数字。
随机数经常配合数组使用,比如随机排列数组元素,可以结合 JS 数组方法 来学习。