Math函数常见的方法
- Math.abs() 获取绝对值
Math.abs(-12) = 12
- Math.ceil() 向上取整
console.log(Math.ceil(1.8)); // 向上取整 2
console.log(Math.ceil(1.2)); // 向上取整 2
- Math.floor() 向下取整
console.log(Math.floor(1.7)); // 向下取整 1
console.log(Math.floor(1.1)); // 向下取整 1
- Math.round() 四舍五入
注意:正数时,包含5是向上取整,负数时包含5是向下取整。
Math.round(-16.3) = -12
Math.round(-16.5) = -12
Math.round(-16.51) = -13
- Math.random() 取[0,1)的随机小数
// 案例1:获取[0,10]的随机整数
Math.round(Math.random()*10);
// 案例2:获取[n,m]之间的随机整数
Math.round(Math.random()*(m-n)+n)
- Math.min() 获取一组数据中的最小值
Math.min(23, 432, 52, 21, 4); //4
- Math.max()获取一组数据中的最大值
Math.min(23, 432, 52, 21, 4); //432
- Math.PI 获取圆周率π 的值
Math.PI
- Math.pow() 获取一个值的多少次幂
Math.pow(10,2); // 100
- Math.sqrt() 对数值开方
ath.sqrt(9); //3