Math常用方法总结

169 阅读1分钟
  1. Math.min()/Math.max();寻找最大最小值;
var arr = ['6','1024',52,256,369]; // 先将内容转换成数组后再比较;
Math.max(arr); // NaN 参数为枚举值,不能直接传数组;
Math.max.apply(this, arr); // 1024 利用apply改造可以直接使用数组
Math.min.apply(this, arr); // 6
  1. Math.round(num): 四舍五入;
  2. Math.sqrt(num): 返回平方根;
  3. Math.pow(num, p): 返回次幂;
  4. Math.floor(num): 下取整;
Math.floor(0.9) // 0
有点类似取整parseInt()
  1. Math.ceil(num): 上取整;
Math.ceil(0.3) // 1
  1. Math.random(): 返回0~1之间的随机数,但不包含0和1;
Math.floor(Math.random() * 10 + 1) // 随机返回1-10之间的随机数,包含1和10;
公式模型:Math.floor(Math.random() * '最大值' + '最小值')
  1. Math.abs(num): 返回绝对值;
  2. Math.trunc(num): 返回整数部分,不会四舍五入,类似Math.floor, ES6新增;
Math.floor(-4.1) // -5
Math.trunc(-4.1) // -4

Math.floor(4.1) // 4
Math.trunc(4.1) // 4