Math的属性
属性 | 描述 |
---|---|
Math.PI | 返回圆周率(约等于3.14159) |
Math.SQRT2 | 返回 2 的平方根(约等于 1.414) |
Math的方法
方法 | 描述 |
---|---|
Math.abs(x) | 返回数的绝对值 |
Math.ceil(x) | 对数进行上舍入 |
Math.floor(x) | 对数进行下舍入 |
Math.round(x) | 把数四舍五入为最接近的整数 |
Math.max(x,y) | 返回 x 和 y 中的最高值 |
Math.min(x,y) | 返回 x 和 y 中的最低值 |
Math.pow(x,y) | 返回 x 的 y 次幂 |
Math.sqrt(x) | 返回数的平方根 |
Math.random() | 返回 0 ~ 1 之间的随机数 |
-
Math.round():负数的四舍五入,一般都是转换为正数处理
console.log(Math.round(-3.5)); // -4+0.5; -3.5 //返回-3 console.log(Math.round(-3.4)); // -4+0.6; -3.4 //返回-3 console.log(Math.round(-3.6)); // -4+0.4; -3.6 //返回-3
-
求数组元素的最大值和最小值
var arr=[3,6,9,1,5,4]; var max=Math.max.apply(null,arr); var min=Math.min.apply(null,arr); console.log(max);
-
两点距离公式
function getDistance(point1,point2){ return Math.sqrt(Math.pow(point2.x-point1.x,2)+Math.pow(point2.y-point1.y,2)); } var point1={x:100,y:100}; var point2={x:200,y:200}; var v=getDistance(point1,point2); console.log(v);
-
2的多少次幂
console.log(1<<2);//返回4 console.log(1<<4);//返回16