JavaScript Math对象属性与方法

ECMAScript还为保存数学公式和信息提供了一个公共位置,即Math对象。与我们再JavaScript直接编写的计算功能相比,Math对象提供的计算功能执行起来要快很多。Math对象还提供了辅助完成这些计算的属性和方法。

Math 对象

Math对象用于执行数学任务。
Math对象并不像Date和String那样是对象的类,因此没有构造函数Math()。

语法

1
2
var x = Math.PI; // 返回圆周率
var y = Math.sprt(16); //返回16的平方根

Math对象的属性

Math对象包含的属性大都是数学计算中可能会用到的一些特殊值。

属性描述
E返回算术常量 e,即自然对数的底数(约等于2.718)。
LN2返回 2 的自然对数(约等于0.693)。
LN10返回 10 的自然对数(约等于2.302)。
LOG2E返回以 2 为底的 e 的对数(约等于 1.414)。
LOG10E返回以 10 为底的 e 的对数(约等于0.434)。
PI返回圆周率(约等于3.14159)。
SQRT1_2返回返回 2 的平方根的倒数(约等于 0.707)。
SQRT2返回 2 的平方根(约等于 1.414)。

Math 对象方法

方法描述
abs(x)返回 x 的绝对值。
acos(x)返回 x 的反余弦值。
asin(x)返回 x 的反正弦值。
atan(x)以介于 -PI/2 与 PI/2 弧度之间的数值来返回 x 的反正切值。
atan2(y,x)返回从 x 轴到点 (x,y) 的角度(介于 -PI/2 与 PI/2 弧度之间)。
ceil(x)对数进行上舍入。
cos(x)返回数的余弦。
exp(x)返回 Ex 的指数。
floor(x)对 x 进行下舍入。
log(x)返回数的自然对数(底为e)。
max(x,y,z,…,n)返回 x,y,z,…,n 中的最高值。
min(x,y,z,…,n)返回 x,y,z,…,n中的最低值。
pow(x,y)返回 x 的 y 次幂。
random()返回 0 ~ 1 之间的随机数。
round(x)把数四舍五入为最接近的整数。
sin(x)返回数的正弦。
sqrt(x)返回数的平方根。
tan(x)返回角的正切。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
console.log("abs() Math对象方法:" + Math.abs(-444));

console.log("acos() Math对象方法:" + Math.acos(0.5));

console.log("asin() Math对象方法:" + Math.asin(0.5));

console.log("atan() Math对象方法:" + Math.atan(1));

console.log("atan2() Math对象方法:" + Math.atan2(1, 1));

console.log("cos() Math对象方法:" + Math.cos(0.5));

console.log("sin() Math对象方法:" + Math.sin(0.5));

console.log("tan() Math对象方法:" + Math.tan(2));

console.log("ceil() Math对象方法:" + Math.ceil(1.1));

console.log("floor() Math对象方法:" + Math.floor(2.1));

console.log("round(x) Math对象方法:" + Math.round(6.5));

console.log("exp(x) Math对象方法:" + Math.exp(2));

console.log("log(x) Math对象方法:" + Math.log(2));

console.log("sqrt(x) Math对象方法:" + Math.sqrt(4));

console.log("pow(x,y) Math对象方法:" + Math.pow(1,2));

console.log("max(x,y) Math对象方法:" + Math.max(1,2));

console.log("min(x,y) Math对象方法:" + Math.min(1,2));

console.log("random() Math对象方法:" + Math.random());