Math对象是javascript中一个内置对象。这边主要是总结一些方法属性,以便后面查看。
Math()对象的属性
| 属性 | 说明 |
|---|---|
| Math.E | 常量e的值 |
| Math.LN10 | 10的自然对数 |
| Math.LN2 | 2的自然对数 |
| Math.LOG2E | 以2为底e的对数 |
| Math.LOG10E | 以10为底e的对数 |
| Math.PI | 圆周率 |
| Math.SQRT1_2 | 1/2的平方根 |
| Math.SQRT2 | 2的平方根 |
Math()对象的方法
min()和max()
min()和max()方法都能接受任意多个数值参数,其中,min()方法返回一组数值中最小的值;max()方法返回一组数值中最大的值。
alert(Math.max(1,2)); //2
alert(Math.min(1,2)); //1如果想要返回一个数组中的最大值或最小值,可以这样使用apply()方法。只要将Math对象作为第一个参数传入,数组作为第二个参数传入即可,如:
var a=[1,4,5,66,3,7];
alert(Math.min.apply(Math,a)); //1
alert(Math.max.apply(Math,a)); //6
舍入方法
| 方法 | 说明 |
|---|---|
| Math.ceil() | 向上舍入 |
| Math.floor() | 向下舍入 |
| Math.round() | 四舍五入 |
var num=2.1;
alert(Math.ceil(num)); //3
alert(Math.floor(num)); //2
alert(Math.round(num)); //2
random()方法
random()方法比较常会用到,用于返回[0,1)区间内的一个随机数。
由此,我们也可以得到任意整数区间内的一个随机数,只要套用下面的公式即可:
值=Math.floor(Math.random()*可能值的总数+第一个可能值);
来看个例子:
//获得一个[1,10]的随机数
var num=Math.floor(Math.random()*10+1);
alert(num);
其他方法
| 方法 | 说明 |
|---|---|
| Math.abs(num) | 返回num的绝对值 |
| Math.exp(num) | 返回Math.E的num次幂 |
| Math.log(num) | 返回num的自然对数 |
| Math.pow(num,power) | 返回num的power次幂 |
| Math.sqrt(num) | 返回num的平方根 |
| Math.acos(x) | 返回x的反余弦 |
| Math.asin(x) | 返回x的反正弦 |
| Math.atan(x) | 返回x的反正切 |
| Math.atan2(y,x) | 返回y/x的反正切 |
| Math.cos(x) | 返回x的余弦值 |
| Math.sin(x) | 返回x的正弦值 |
| Math.tan(x) | 返回x的正切值 |
本文详细介绍了JavaScript中的Math对象,包括其属性(如E、PI等)及方法(如min、max、ceil、floor等),并提供了应用实例。
560

被折叠的 条评论
为什么被折叠?



