js中Math方法的一些常见用法总结
//获取[0,1)的随机数
Math.random() //0.6770012720991732
//如果需要保留两位小数,使用num.toFixed(2) -- (四舍五入)
//获取[min,max)的随机数
function myRandom(min,max) {
return Math.random()*(max-min)+min
}
console.log(myRandom(10,20));//15.958826710283756
//---------------------------
//如果需要(min,max],则结果向上取整
//需要[min,max],则四舍五入取整
//向上取整,只要有小数,就向上进1
Math.ceil(3.001); //4
//向下取整,只保留整数部分
Math.floor(3.999); //3
//四舍五入取整
Math.round(3.12); //3
//绝对值
Math.abs(-100); //100
//一组数中的最大值
Math.max(1,2,36,7); //36
//一组数中的最小值
Math.min(1,2,36,7); //1
//num的power次幂
Math.pow(3,2); //9
//参数的平方根
Math.sqrt(9); //3
ES6新增不常用的一些Math方法
//Math.trunc()方法返回一个数字的证书部分(不四舍五入),不是数值转数值,不饿能转数值的返回NaN
Math.trunc(4.1)//4
Math.trunc(4.9)//4
Math.trunc(-4.1)//-4
Math.trunc(-0.1)//0
Math.trunc('12.13')//12
Math.trunc(NaN)//NaN
Math.trunc('qwe')//NaN
Math.trunc()//NaN
//Math.sign()方法用来判断一个数是正数还是负数,正数返回+1;负数返回-1。不是数字转换数字后判断,无法转换返回NaN
Math.sign(-5)//-1
Math.sign(5)//+1
Math.sign(-0)//-1
Math.sign(+0)//+1
Math.sign('5')//+1
Math.sign(NaN)//NaN
Math.sign('qwe')//NaN
Math.sign()//NaN
//Math.cbrt()返回一个数字的立方根,如果不是数字用Number转换,不能转换的返回NaN
Math.cbrt(-1)//-1
Math.cbrt(0)//0
Math.cbrt('8')//2
Math.cbrt('qwe')//NaN