JavaScript中Math对象经常使用方法总结

1,Math.pow(2, 53)     // => 2的53次幂

2,Math.pow(3, 1/3)     // => 3的立方根

3,Math.sqrt(3)      // => 3的平方根

4, Math.round(0.7)      // => 1.0 四舍五入

5, Math.ceil(0.7)     // => 1.0 向上取整

6, Math.floor(0.6)      // => 0.0 向下取整

7,Math.abs(-5)     // => 求绝对值

8,Math.max(a, b, c)      // 求最大值

9,Math.min(a, b, c)      //求最小值

10,Math.random()      // 大于0小于1的随机数

11,Math.sin(0),Math.cos, Math.atan // 经常使用的三角函数

12,Math.log(10)      // 10的天然对数

13,Math.PI()      // 圆周率

14,Math.exp(3)      // e的三次幂

例如(1) Math.ceil和Math.round的比较:

Math.ceil(25.1) = 26
     Math.round(25.1) = 25
复制代码

例如(2) Math.random()经常使用公式:求在某一范围随机数

Math.floor(Math.random()*总数 + 第一个数)
     Math.floor(Math.random() * 10 + 5) // 5~14之间的任意数
     function selectRandom(lower, upper) {
        var sum = upper - lower + 1
        return Math.floor(Math.random() * sum + lower)
     }
     for(var i = 0; i< 20; i ++ ){
        document.write(selectRandom(1, 20));
        document.write('<br/>')
      }
复制代码
相关文章
相关标签/搜索