Math 对象用作多个数学函数的命名空间。本章对此进行概述。
Math 的属性如下:
Math.E
Math.LN2
Math.LN10
Math.LOG2E
Math.LOG10E
Math.PI
Math.SQRT1_2
Math.SQRT2
Math 的数值函数包括以下内容:
Math.abs(x)
x 的绝对值。Math.ceil(x)
> Math.ceil(3.999) 4 > Math.ceil(3.001) 4 > Math.ceil(-3.001) -3 > Math.ceil(3.000) 3
有关将浮点数转换为整数的更多信息,请参阅转换为整数。
Math.exp(x)
Math.E)。这是 Math.log() 的反函数。Math.floor(x)
> Math.floor(3.999) 3 > Math.floor(3.001) 3 > Math.floor(-3.001) -4 > Math.floor(3.000) 3
有关将浮点数转换为整数的更多信息,请参阅转换为整数。
Math.log(x)
x 的自然(以欧拉常数为底)对数 ln(x)。这是 Math.exp() 的反函数。Math.pow(x, y)
返回 xy,x的 y 次幂:
> Math.pow(9, 2) 81 > Math.pow(36, 0.5) 6
Math.round(x)
返回四舍五入到最接近整数的 x(如果它在两个整数之间,则为较大的一个):
> Math.round(3.999) 4 > Math.round(3.001) 3 > Math.round(3.5) 4 > Math.round(-3.5) -3
有关将浮点数转换为整数的更多信息,请参阅转换为整数。
Math.sqrt(x)
返回
,x 的平方根:
> Math.sqrt(256) 16
三角函数方法接受并返回以弧度为单位的角度。以下函数展示了如何在需要的情况下实现转换:
从度数到弧度
functiontoRadians(degrees){returndegrees/180*Math.PI;}
以下是交互
> toRadians(180) 3.141592653589793 > toRadians(90) 1.5707963267948966
从弧度到度数
functiontoDegrees(radians){returnradians/Math.PI*180;}
以下是交互
> toDegrees(Math.PI * 2) 360 > toDegrees(Math.PI) 180
三角函数方法如下
以下是其余的 Math 函数:
Math.min(x1?, x2?, ...)
返回参数中最小的数字:
> Math.min() Infinity > Math.min(27) 27 > Math.min(27, -38) -38 > Math.min(27, -38, -43) -43
通过 apply() 在数组上使用它(请参阅func.apply(thisValue, argArray))
> Math.min.apply(null, [27, -38, -43]) -43
Math.max(x1?, x2?, ...)
返回参数中最大的数字:
> Math.max() -Infinity > Math.max(7) 7 > Math.max(7, 10) 10 > Math.max(7, 10, -333) 10
通过 apply() 在数组上使用它(请参阅func.apply(thisValue, argArray))
> Math.max.apply(null, [7, 10, -333]) 10
Math.random()
返回一个伪随机数 r,0 ≤ r < 1。以下函数使用 Math.random() 来计算一个随机整数:
/*** Compute a random integer within the given range.** @param [lower] Optional lower bound. Default: zero.* @returns A random integer i, lower ≤ i < upper*/functiongetRandomInteger(lower,upper){if(arguments.length===1){upper=lower;lower=0;}returnMath.floor(Math.random()*(upper-lower))+lower;}