js Math方法

前言

Math全部都是静态属性和方法
Math是一种静态类,该类别不能实例化

Math的属性

  • E 返回算术常量 e,即自然对数的底数(约等于2.718)。
  • LN2 返回 2 的自然对数(约等于0.693)。
  • LN10 返回 10 的自然对数(约等于2.302)。
  • LOG2E 返回以 2 为底的 e 的对数(约等于 1.414)。
  • LOG10E 返回以 10 为底的 e 的对数(约等于0.434)。
  • PI 返回圆周率(约等于3.14159)。
  • SQRT1_2 返回返回 2 的平方根的倒数(约等于 0.707)。
  • SQRT2 返回 2 的平方根(约等于 1.414)。
//常用的Math的属性有以下
console.log(Math.PI);//3.141592653589793
console.log(Math.SQRT2);//1.4142135623730951

Math的方法

  • abs(x) 返回数的绝对值。
  • acos(x) 返回数的反余弦值。
  • asin(x) 返回数的反正弦值。
  • atan(x) 以介于 -PI/2 与 PI/2 弧度之间的数值来返回 x 的反正切值。
  • atan2(y,x) 返回从 x 轴到点 (x,y) 的角度(介于 -PI/2 与 PI/2 弧度之间)。
  • ceil(x) 对数进行上舍入。
  • cos(x) 返回数的余弦。
  • exp(x) 返回 e 的指数。
  • floor(x) 对数进行下舍入。
  • log(x) 返回数的自然对数(底为e)。
  • max(x,y) 返回 x 和 y 中的最高值。
  • min(x,y) 返回 x 和 y 中的最低值。
  • pow(x,y) 返回 x 的 y 次幂。
  • random() 返回 0 ~ 1 之间的随机数。
  • round(x) 把数四舍五入为最接近的整数。
  • sin(x) 返回数的正弦。
  • sqrt(x) 返回数的平方根。
  • tan(x) 返回角的正切。

需要注意的是 Math.round ( ) ,当参数为负数时,该方法会先将负小数转化成负整数跟小数,分开四舍五入计算后相加,得出结果。例如 Math.round(-3.6) = =>Math.round ( -4 ) + Math.round (0.4) = => - 4

//常用的Math的方法有:
console.log(Math.abs(-5));//绝对值
//相当于if(a<0) a=-a;

//round 四舍五入,只认整数,整数跟小数分开四舍五入后相加
console.log(Math.round(3.3));//3 四舍五入
console.log(Math.round(-3.5));//-3 相当于Math.round(-4+0.5) -4+1
console.log(Math.round(-3.6));//-4 相当于Math.round(-4+0.4) -4+0

console.log(Math.floor(3.6));//3 向下取整
console.log(Math.ceil(3.6));//4 向上取整

console.log(Math.max(2,3,4,5,7));//7 求最大值 
console.log(Math.min(2,3,4,5,7));//2 求最小值 

var arr=[1,2,3,4,5,6,7];
console.log(Math.max.apply(null,arr));//求数组中的最大值
console.log(Math.min.apply(null,arr));//求数组中的最小值

console.log(Math.sqrt(9));//求9的平方根,普通的平方根用这个,速度比Math.pow快

console.log(Math.pow(2,2));//求2的2次幂,可以求任意数的任意次幂
console.log(Math.pow(4,0.5));//求平方根
console.log(Math.pow(4,1/3));//求立方根

console.log(1<<2);//速度快,求2的2次幂,只能求2的次幂

console.log(Math.random());//0-1的随机数,官方文档说包括0,但不包含1
console.log(Math.floor(Math.random()*50));//0-49之间的随机数
console.log(Math.ceil(Math.random()*50));//1-50之间的随机数

扩展

上面说 Math 全部都是静态属性和方法,下面来回顾一下什么叫静态方法:

静态方法也叫类的方法,是指把构造函数看成对象,增加的方法。例如数组中的 Array.from ( )、Array.isArray ( ) 。
除此之外还有实例化方法,例如 forEach()、map()。

var arr=new Array(1,2,3);
//或者 var arr=[1,2,3]
arr.forEach(function(){

})

简单来记,静态方法都是 类型.方法名(Array.from())

发布了46 篇原创文章 · 获赞 26 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Charissa2017/article/details/103835112