JavaScript Math 对象
Math
是 JavaScript 的内置对象,提供一系列数学常数和数学方法。该对象不是构造函数,不能生成实例,所有的属性和方法都必须在 Math
对象上调用,如 Math.floor(4.14)、Math.sqrt(16)...
Math 对象属性
属性 |
描述 |
E |
返回算术常量 e,即自然对数的底数(约等于 2.718281828459045 )。 |
LN2 |
返回 2 的自然对数(约等于 0.6931471805599453)。 |
LN10 |
返回 10 的自然对数(约等于 2.302585092994046)。 |
LOG2E |
返回以 2 为底的 e 的对数(约等于 1.4426950408889634)。 |
LOG10E |
返回以 10 为底的 e 的对数(约等于 0.4342944819032518 )。 |
PI |
返回圆周率(约等于 3.141592653589793)。 |
SQRT1_2 |
返回 2 的平方根的倒数(约等于 0.7071067811865476)。 |
SQRT2 |
返回 2 的平方根(约等于 1.4142135623730951)。 |
Math 对象方法
方法 |
描述 |
abs(x) |
返回 x 的绝对值。如果 x 不是数字或者为 undefined ,则返回 NaN,如果 x 为 null 返回 0。 |
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 进行下舍入。返回小于等于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(不包含) 之间的一个随机小数,如 0.8110480700433211 |
round(x) |
四舍五入。 |
sin(x) |
返回数的正弦。 |
sqrt(x) |
返回数的平方根。 |
tan(x) |
返回角的正切。 |
编码示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<title>测试</title>
<script>
/**返回圆周率(约等于 3.141592653589793)*/
let pi_v = Math.PI;
/**返回算术常量 e,即自然对数的底数(约等于 2.718281828459045 )*/
let e_v = Math.E;
console.log("e=" + e_v, "pi=" + pi_v);
/**输出:10 20 30 NaN 0 NaN*/
console.log(Math.abs(10), Math.abs(-20), Math.abs("30"), Math.abs("40abc"), Math.abs(null), Math.abs(undefined));
/**输出:1 1 2 -0 -0 -5 49*/
console.log(Math.ceil(0.1), Math.ceil(0.8), Math.ceil(2), Math.ceil(-0.1), Math.ceil(-0.8), Math.ceil(-5), Math.ceil("48.9"));
/**输出:0 0 2 -1 -1 -5 48*/
console.log(Math.floor(0.1), Math.floor(0.8), Math.floor(2), Math.floor(-0.1), Math.floor(-0.8), Math.floor(-5), Math.floor("48.9"));
/**输出:3 5 6 -3 -4 -6 -10 20 100*/
console.log(Math.round(2.60), Math.round(4.50), Math.round(6.49),
Math.round(-2.60), Math.round(-4.50), Math.round(-6.49),
Math.round(-10), Math.round(20), Math.round(100.0));
/**输出[0,1]的随机整数
* 输出[0,100]的随机整数
* 输出[50,100]的随机整数*/
console.log("[0,1]:" + Math.round(Math.random()));
console.log("[0,100]:" + Math.round((Math.random() * 100)));
console.log("[50,100]:" + Math.round((Math.random() * 50) + 50));
</script>
</head>
<body>
</body>
</html>