【相关推荐:javascript视频教程、web前端】
math对象是javascript的内置对象,提供一系列数学常数和数学方法。
该对象不是构造函数,所以不能生成实例,所有的属性和方法都必须在math对象上调用。
new math()// typeerror: object is not a function
上面代码表示,math不能当作构造函数用。
属性math对象提供以下一些只读的数学常数。
e:常数e。
ln2:2的自然对数。
ln10:10的自然对数。
log2e:以2为底的e的对数。
log10e:以10为底的e的对数。
pi:常数pi。
sqrt1_2:0.5的平方根。
sqrt2:2的平方根。
这些常数的值如下。
math.e // 2.718281828459045math.ln2 // 0.6931471805599453math.ln10 // 2.302585092994046math.log2e // 1.4426950408889634math.log10e // 0.4342944819032518math.pi // 3.141592653589793math.sqrt1_2 // 0.7071067811865476math.sqrt2 // 1.4142135623730951
方法math对象提供以下一些数学方法。
round方法
round方法用于四舍五入。
math.round(0.1) // 0math.round(0.5) // 1
它对于负值的运算结果与正值略有不同,主要体现在对.5的处理。
math.round(-1.1) // -1math.round(-1.5) // -1
abs方法,max方法,min方法
abs方法返回参数值的绝对值。
math.abs(1) // 1math.abs(-1) // 1
max方法返回最大的参数,min方法返回最小的参数。
math.max(2, -1, 5) // 5math.min(2, -1, 5) // -1
floor方法,ceil方法
floor方法返回小于参数值的最大整数。
math.floor(3.2) // 3math.floor(-3.2) // -4
ceil方法返回大于参数值的最小整数。
math.ceil(3.2) // 4math.ceil(-3.2) // -3
pow方法,sqrt方法
power方法返回以第一个参数为底数、第二个参数为幂的指数值。
math.pow(2, 2) // 4math.pow(2, 3) // 8
sqrt方法法返回参数值的平方根。如果参数是一个负值,则返回nan。
math.sqrt(4) // 2math.sqrt(-4) // nan
log方法,exp方法
log方法返回以e为底的自然对数值。
math.log(math.e) // 1math.log(10) // 2.302585092994046
求以10为底的对数,可以除以math.ln10;求以2为底的对数,可以除以math.ln2。
math.log(100)/math.ln10 // 2math.log(8)/math.ln2 // 3
exp方法返回常数e的参数次方。
math.exp(1) // 2.718281828459045math.exp(3) // 20.085536923187668
random方法
该方法返回0到1之间的一个伪随机数,可能等于0,但是一定小于1。
math.random() // 0.7151307314634323// 返回给定范围内的随机数function getrandomarbitrary(min, max) { return math.random() * (max - min) + min;}// 返回给定范围内的随机整数function getrandomint(min, max) { return math.floor(math.random() * (max - min + 1)) + min;}
三角函数方法
sin方法返回参数的正弦,cos方法返回参数的余弦,tan方法返回参数的正切。
math.sin(0) // 0math.cos(0) // 1math.tan(0) // 0
asin方法返回参数的反正弦,acos方法返回参数的反余弦,atan方法返回参数的反正切。这个三个方法的返回值都是弧度值。
math.asin(1) // 1.5707963267948966math.acos(1) // 0math.atan(1) // 0.7853981633974483
【相关推荐:javascript视频教程、web前端】
以上就是简单聊聊javascript的math对象方法的详细内容。
