JavaScript Math 对象
JavaScript Math 对象允许您对数字执行数学任务。
Math对象是全局对象。
与其他全局对象不同,Math对象没有构造函数。方法和属性是 静态 的。
可以在不首先创建Math对象的情况下使用所有方法和属性(常量)。
一.Math对象的方法
1.Math.round()
Math.round(x)
的返回值是 x 四舍五入为最接近的整数。
Math.round(6.8); // 返回 7
Math.round(2.3); // 返回 2
2.Math.pow()
Math.pow(x, y)
的返回值是 x 的 y 次幂。
Math.pow(8, 2); // 返回 64
3.Math.sqrt()
Math.sqrt(x)
返回 x 的平方根。
Math.sqrt(64); // 返回 8
4.Math.abs()
Math.abs(x)
返回 x 的绝对(正)值:
Math.abs(-4.7); // 返回 4.7
5.Math.ceil()
Math.ceil(x)
的返回值是 x 上舍入最接近的整数。
Math.ceil(6.4); // 返回 7
6.Math.floor()
Math.floor(x)
的返回值是 x 下舍入最接近的整数。
Math.floor(2.7); // 返回 2
7.Math.sin() 和 Math.cos()
Math.sin(x)
返回角 x(以弧度计)的正弦(介于 -1 与 1 之间的值)。
Math.cos(x)
返回角 x(以弧度计)的余弦(介于 -1 与 1 之间的值)。
要使用角度替代弧度,则需要将角度转换为弧度:
Angle in radians = Angle in degrees x PI / 180. //通用
例子:
Math.sin(90 * Math.PI / 180); // 返回 1(90 度的正弦)
Math.cos(0 * Math.PI / 180); // 返回 1(0 度的余弦)
8.Math.min() 和 Math.max()
Math.min()
和 Math.max()
可用于查找参数列表中的最低或最高值。
Math.min(0, 450, 35, 10, -8, -300, -78); // 返回 -300
Math.max(0, 450, 35, 10, -8, -300, -78); // 返回 450
9.Math.random()
Math.random()
返回介于 0(包括) 与 1(不包括) 之间的随机数。
Math.random()
总是返回小于 1 的数。
10.其他方法
方法 | 描述 |
---|---|
acos(x) | 返回 x 的反余弦值,以弧度计 |
asin(x) | 返回 x 的反正弦值,以弧度计 |
atan(x) | 以介于 -PI/2 与 PI/2 弧度之间的数值来返回 x 的反正切值。 |
atan2(y,x) | 返回从 x 轴到点 (x,y) 的角度 |
exp(x) | 返回 Ex 的值 |
log(x) | 返回 x 的自然对数(底为e) |
tan(x) | 返回角的正切 |
二、Math 属性(常量)
JavaScript 提供了可由 Math 对象访问的 8 个数学常量:
●Math.E
:返回欧拉指数(Euler’s number)
●Math.PI
:返回圆周率(PI) ( 返回 3.141592653589793)
●Math.SQRT2
: 返回 2 的平方根
●Math.SQRT1_2
: 返回 1/2 的平方根
●Math.LN2
:返回 2 的自然对数
●Math.LN10
:返回 10 的自然对数
●Math.LOG2E
:返回以 2 为底的 e 的对数(约等于 1.414)
●Math.LOG10E
:返回以 10 为底的 e 的对数(约等于0.434)
三、JS随机
1.0~1的随机数
Math.random()
返回 0(包括) 至 1(不包括) 之间的随机数。
Math.random()
总是返回小于 1 的数。
Math.random(); // 返回随机数
2.随机整数
Math.random()
与 Math.ceil()、Math.floor()
一起使用用于返回随机整数。
例1:Math.floor(Math.random() * 10); // 返回 0 至 9 之间的数
例2:
Math.floor(Math.random() * 11); // 返回 0 至 10 之间的数
等于 Math.ceil(Math.random() * 10));
例3:Math.floor(Math.random() * 10) + 1; // 返回 1 至 10 之间的数
3.随机函数
创建一个随机函数用于生成所有随机整数:
(1)始终返回介于 min(包括)和 max(不包括)之间的随机数:
Math.floor(Math.random() * (max - min) ) + min
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min) ) + min;
}
(2)始终返回介于 min 和 max(都包括)之间的随机数:
Math.floor(Math.random() * (max - min + 1) ) + min
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1) ) + min;
}