JavaScript

JS Math(数学)对象

下文笔者讲述JavaScript中Math对象的简介说明,如下所示

JavaScript Math对象简介说明

 
Math是JavaScript中的一个内置对象
   Math对象中提供数学中常用的信息,
     如:PI常量值、数学函数、平均数、绝对值、四舍五入等操作方法
下面笔者将通过示例的方式一一讲解Math对象中的方法及属性,如下所示
var pi_val = Math.PI;                 // 数学中 π 的值:3.141592653589793
var abs_val = Math.sin(-5.35);  // -5.35 的绝对值:5.35

Math对象中属性

属性 备注
E 返回算术常量 e,即自然对数的底数(约等于 2.718)
LN2 返回 2 的自然对数(约等于 0.693)
LN10 返回 10 的自然对数(约等于 2.302)
LOG2E 返回以 2 为底的 e 的对数(约等于 1.443)
LOG10E 返回以 10 为底的 e 的对数(约等于 0.434)
PI 返回圆周率 π(约等于 3.14159)
SQRT1_2 返回返回 2 的平方根的倒数(约等于 0.707)
SQRT2 返回 2 的平方根(约等于 1.414)
document.write(Math.E + "<br>");            // 输出:2.718281828459045
document.write(Math.LN2 + "<br>");          // 输出:0.6931471805599453
document.write(Math.LN10 + "<br>");         // 输出:2.302585092994046
document.write(Math.LOG2E + "<br>");        // 输出:1.4426950408889634
document.write(Math.LOG10E + "<br>");       // 输出:0.4342944819032518
document.write(Math.PI + "<br>");           // 输出:3.141592653589793
document.write(Math.SQRT1_2 + "<br>");      // 输出:0.7071067811865476
document.write(Math.SQRT2 + "<br>");        // 输出:1.4142135623730951

Math对象中方法说明

方法 备注
abs(x) 返回 x 的绝对值
acos(x) 返回 x 的反余弦值
acosh(x) 返回 x 的反双曲余弦值
asin(x) 返回 x 的反正弦值
asinh(x) 返回 x 的反双曲正弦值
atan(x) 返回 x 的反正切值
atanh(x) 返回 x 的反双曲正切值
atan2(y,x) 返回 y/x 的反正切值
cbrt(x) 返回 x 的立方根
ceil(x) 对 x 进行向上取整,即返回大于 x 的最小整数
clz32(x) 返回将 x 转换成 32 无符号整形数字的二进制形式后,开头 0 的个数
cos(x) 返回 x 的余弦值
cosh(x) 返回 x 的双曲余弦值
exp(x) 返回算术常量 e 的 x 次方,即 Ex
expm1(x) 返回 exp(x) - 1 的值
floor(x) 对 x 进行向下取整,即返回小于 x 的最大整数
fround(x) 返回最接近 x 的单精度浮点数
hypot([x, [y, [...]]]) 返回所有参数平方和的平方根
imul(x, y) 将参数 x、y 分别转换位 32 位整数,并返回它们相乘后的结果
log(x) 返回 x 的自然对数
log1p(x) 返回 x 加 1 后的自然对数
log10(x) 返回 x 以 10 为底的对数
log2(x) 返回 x 以 2 为底的对数
max([x, [y, [...]]]) 返回多个参数中的最大值
min([x, [y, [...]]]) 返回多个参数中的最小值
pow(x,y) 返回 x 的 y 次幂
random() 返回一个 0 到 1 之间的随机数
round(x) 返回 x 四舍五入后的整数
sign(x) 返回 x 的符号,即一个数是正数、负数还是 0
sin(x) 返回 x 的正弦值
sinh(x) 返回 x 的双曲正弦值
sqrt(x) 返回 x 的平方根
tan(x) 返回 x 的正切值
tanh(x) 返回 x 的双曲正切值
toSource() 返回字符串"Math"
trunc(x) 返回 x 的整数部分
valueOf() 返回 Math 对象的原始值
例:
document.write(Math.abs(-4.287) + "<br>");              
document.write(Math.acos(0.6) + "<br>");                
document.write(Math.ceil(1.23) + "<br>");               
document.write(Math.exp(1) + "<br>");                  
document.write(Math.floor(4.88) + "<br>");              
document.write(Math.log(8) + "<br>");                   
document.write(Math.max(2, 80, 11, 19) + "<br>");           
document.write(Math.min(2, 80, 11, 19) + "<br>");           
document.write(Math.random() + "<br>");                  
document.write(Math.pow(3, 4) + "<br>");                
document.write(Math.sign(-46) + "<br>");              
document.write(Math.sqrt(234) + "<br>"); 
javascript之Math对象的简介说明