Math 对象提供了数学常量和函数的属性和方法。与其它全局对象不同的是,Math 不是一个构造函数。Math 的所有属性和方法都是静态的,因此可以直接作为对象来调用而无需创建它。
例如,可以这样引用圆周率:Math.PI;这样调用正弦函数:Math.sin(x),其中 x 是方法的参数。
语法
调用 Math 属性和方法的语法如下:
var pi_val = Math.PI;
var sine_val = Math.sin(30);
JavaScript Math 属性
下面列出了 Math 类的一些属性:
| 序号 |
名称 & 描述 |
| 1 |
E |
| 2 |
LN2 |
| 3 |
LN10 |
| 4 |
LOG2E |
| 5 |
LOG10E |
| 6 |
PI |
| 7 |
SQRT1_2 |
| 8 |
SQRT2 |
JavaScript Math 方法
下面列出了 Math 类的一些方法:
| 序号 |
名称 & 描述 |
| 1 |
abs() |
| 2 |
acos() |
| 3 |
acosh() |
| 4 |
asin() |
| 5 |
asinh() |
| 6 |
atan() |
| 7 |
atan2() |
| 8 |
atanh() |
| 9 |
cbrt() |
| 10 |
ceil() |
| 11 |
clz32() |
| 12 |
cos() |
| 13 |
cosh() |
| 14 |
exp() |
| 15 |
expm1() |
| 16 |
floor() |
| 17 |
fround() |
| 18 |
hypot() |
| 19 |
imul() |
| 20 |
log() |
| 21 |
log10() |
| 22 |
log1p() |
| 23 |
log2() |
| 24 |
max() |
| 25 |
min() |
| 26 |
pow() |
| 27 |
random() |
| 28 |
round() |
| 29 |
sign() |
| 30 |
sin() |
| 31 |
sinh() |
| 32 |
sqrt() |
| 33 |
tan() |
| 34 |
tanh() |
| 35 |
trunc() |
在接下来的部分中,我们将通过几个例子来展示与 Math 相关的方法的使用。
示例(Math 对象属性)
下面的例子展示了 Math 对象每个属性的常量值。
在这里,我们访问了 E、LN2 和 PI 属性的值。
<html>
<head>
<title>JavaScript - Math 对象的属性</title>
</head>
<body>
<p id="output"></p>
<script>
document.getElementById("output").innerHTML =
"Math.E == " + Math.E + "<br>" +
"Math.LN2 == " + Math.LN2 + "<br>" +
"Math.LN10 == " + Math.LN10 + "<br>" +
"Math.PI == " + Math.PI + "<br>"+
"Math.LOG2E == " + Math.LOG2E + "<br>" +
"Math.LOG10E == " + Math.LOG10E;
</script>
</body>
</html>
输出 执行上述程序后,它将返回提供的 Math 属性的值。
示例(Math ceil() 方法)
这里,我们计算 Math.ceil() 方法来返回比传入参数更大的最小整数值。对于值 5.9,方法返回 6。
<html>
<head>
<title>JavaScript - Math.ceil() 方法</title>
</head>
<body>
<p id="output"></p>
<script>
let ans = Math.ceil(5.9);
document.getElementById("output").innerHTML =
"Math.ceil(5.9) = " + ans;
</script>
</body>
</html>
输出 执行上述程序后,结果返回为 6。
示例(Math max() 方法)
Math.max() 方法用于获取作为数组传递的所有参数中的最大值。
这里,我们向 Math.max() 对象传递了六个参数,方法返回了它们中的最大值。
<html>
<head>
<title>JavaScript - Math.max() 方法</title>
</head>
<body>
<p id="output"></p>
<script>
let ans = Math.max(100, 10, -5, 89, 201, 300);
document.getElementById("output").innerHTML =
"Math.max(100, 10, -5, 89, 201, 300) = " + ans + "<br>";
</script>
</body>
</html>
输出 执行上述程序后,返回的最大值为 300。
示例(Math.cos() 方法)
Math.cos() 方法返回作为参数传递的数字的余弦值。0 的余弦值是 1,这在下面示例的输出中可以看到。
<html>
<head>
<title>JavaScript - Math.cos() 方法</title>
</head>
<body>
<p id="output"></p>
<script>
let ans = Math.cos(0);
document.getElementById("output").innerHTML = "Math.cos(0) = " + ans;
</script>
</body>
</html>
输出 如果执行上述程序,结果返回为 "1"。