随机数
#随机数函数
const randomInRange = (min, max) => {
return Math.floor(Math.random() * (max - min) + min)
}
#可返回介于 0(包含) ~ 1(不包含) 之间的一个随机数
Math.random()
Math.trunc()
Math.trunc方法用于去除一个数的小数部分,返回整数部分。
Math.trunc(4.1) // 4
Math.trunc(4.9) // 4
Math.trunc(-4.1) // -4
Math.trunc(-4.9) // -4
Math.trunc(-0.1234) // -0
对于非数值,Math.trunc内部使用Number方法将其先转为数值。
Math.trunc('123.456') // 123
Math.trunc(true) //1
Math.trunc(false) // 0
Math.trunc(null) // 0
对于空值和无法截取整数的值,返回NaN。
Math.trunc(NaN); // NaN
Math.trunc('foo'); // NaN
Math.trunc(); // NaN
Math.trunc(undefined) // NaN
对于没有部署这个方法的环境,可以用下面的代码模拟。
Math.trunc = Math.trunc || function(x) {
return x < 0 ? Math.ceil(x) : Math.floor(x);
};
Math.round()
可把一个数字四舍五入
Math.round(x)
console.log(Math.round(25.9)); // 26
console.log(Math.round(25.5)); // 26
console.log(Math.round(25.1)); // 25
Math.pow()
返回 x 的 y 次幂
Math.pow(x,y)
Math.ceil()
可对一个数进行上舍入,取整
Math.ceil(x)
console.log(Math.ceil(25.9)); // 26
console.log(Math.ceil(25.5)); // 26
console.log(Math.ceil(25.1)); // 26
Math.floor()
可对一个数进行向下取整
Math.floor(x)
Math.max()
可返回两个指定的数中带有较大的值的那个数
Math.max(n1,n2,n3,...,nX)
Math.min()
可返回指定的数字中带有最小值的数字
Math.min(n1,n2,n3,...,nX)
Math.sqrt()
可返回一个数的平方根
Math.sqrt(x)
Math.abs()
可返回一个数的绝对值
Math.abs(x)
Math.tan()
可返回一个表示某个角的正切的数字
Math.tan(x)
Math.sin()
参数 x 的正弦值,返回值在 -1.0 到 1.0 之间
Math.sin(x)
Math.log()
可返回一个数的自然对数(基于E)
Math.log(x)
Math.exp()
可返回 e 的 x 次幂的值。 E 为自然底数 (近似值 2.7183)
Math.exp(x)
Math.cos()
可返回一个数字的余弦值,返回的是 -1.0 到 1.0 之间的数
Math.cos(x)
Math.acos()
返回一个数的反余弦。返回的值是 0 到 PI 之间的弧度值
Math.acos(x)
Math.asin()
返回-PI/2 到 PI/2 之间的弧度值
Math.asin(x)
Math.atan()
以介于 -PI/2 与 PI/2 弧度之间的数值来返回 x 的反正切值
Math.atan(x)
Math.atan2()
可返回数字的反正切值
Math.atan2(y,x)