Math是用来执行数学任务的,Math不是对象的类,所以没有像Date和String那样的构造函数,可以理解为Math是javaScript的内置对象,无需创建,直接使用就可以了;或者可以理解为Math提供的属性和方法都是静态的,只需要类名调用就可以了。
属性:
Math.E : 常量e ,返回值约为:2.718281828459045
Math.PI:常量圆周率,返回值约为:3.141592653589793
Math.SQRT2: 2的平方根,返回值约为:1.4142135623730951
还有好几个不常用的可以在W3C上查看http://www.w3school.com.cn/jsref/jsref_obj_math.asp
方法:
常用方法:
Math.random() :返回0-1之间的随机数
console.log(Math.random()*5+1);
输出一个1到6之间的随机数
Math.ceil(x):向上求余,不进行四舍五入,只要有小数就向前进一位(分页的时候适合求页数)
console.log(Math.ceil(2.3333333333333333));
console.log(Math.ceil(0.1111111111111111));
输出
Math.floor(x):向下舍去,不进行四舍五入,直接去掉小数位,取整数
console.log(Math.floor(2.999999999));
console.log(Math.floor(0.999999999));
输出
Math.round(x):对数值进行四舍五入操作
console.log(Math.round(2.999999999));
console.log(Math.round(0.499999999));
输出
Math.max(x,y);Math.min():比较两个数的最大和最小值
console.log(Math.max(2.999999999,3));
console.log(Math.min(0.999999999,1));
输出
Math.pow(x,y):求次方,返回 x 的 y 次幂。
console.log(Math.pow(2,3));
console.log(Math.pow(1/2,2));
输出
Math.sqrt(x):对数进行开平方,返回数的平方根
console.log(Math.sqrt(4));
console.log(Math.sqrt(1/2));
输出
三角函数:
abs(x) | 返回数的绝对值。 |
acos(x) | 返回数的反余弦值。 |
asin(x) | 返回数的反正弦值。 |
atan(x) | 以介于 -PI/2 与 PI/2 弧度之间的数值来返回 x 的反正切值。 |
atan2(y,x) | 返回从 x 轴到点 (x,y) 的角度(介于 -PI/2 与 PI/2 弧度之间) |
cos(x) | 返回数的余弦。 |
sin(x) | 返回数的正弦。 |
tan(x) | 返回角的正切。 |