JS中Math的常用方法
Math是js的一个内置对象,它提供了一些数学属性和方法,可以对数字进行计算(用于Number类型)。math和其他全局对象不同,他不是一个构造器,Math的所有方法和属性都是静态的,直接使用并传入对应的参数。
1、Math.abs()
Math.abs()获取绝对值
Math.abs(-12) // 12
Math.abs(-100) // 100
2、Math.ceil()/Math.floor()
Math.ceil()向上取整,Math.floor()向下取整
Math.ceil(12.03) //13
math.ceil(12.91) //13
Math.floor(12.04) //12
Math.floor(12.98) //12
3、Math.round()
Math.round()四舍五入(正数时,包含五向上取整,负数时包含五向下取整)
Math.round(-10.3) //-10
Math.round(-10.5) //-10
Math.round(-10.9) //-11
Math.round(10.3) //10
Math.round(10.5) //11
4、Math.random()
Math.random()取[0,1)的随机小数。如果想大于这个范围的话,可以套用公式:Math.floor(Math.random()*总数+第一个值)
Math.random(); //产生[0,1)之间的随机数
Math.random()*(n-m)+m //返回指定范围的随机数(m-n之间)
Math.floor(Math.random()*10+1) //随机产生0-10之间的任意数
for(var i = 0;i < 10;i++) {
document.write(Math.floor(Math.random()*10+5)); //5-14之间的任意数
}
5、Math.max()/Matn.min()
Math.max()取最大值,Math.min()取最小值
Math.max(10,1,9,6,4,23,12) //23
Matn.min(10,1,9,6,4,23,12) //1
6、Math.PI
Math.PI获取圆周率π的值
console.log(Math.PI) // 3.141592653589793
6、Math.pow()
Math.pow()获取一个值的多少次幂
Math.pow(10²) //100
7、Math.sqrt()
Math.sqrt()对数值开方
Math.sqrt(100) //10
Mart.sqrt(64) //8