JavaScript 之 Math对象

Math对象

  Math 对象不是构造函数,它具有数学常数和函数的属性和方法,都是以静态成员的方式提供。

常用方法:

Math.PI             // 圆周率
Math.random()       // 生成随机数,生成0~1之间的随机数,包含0,不含1
Math.floor()        // 向下取整
Math.ceil()         // 向上取整
Math.round()        // 取整,四舍五入
Math.abs()          // 取绝对值
Math.max()          // 求最大值
Math.min()          // 求最小值
Math.sin()          // 求正弦值
Math.cos()          // 求余弦值
Math.power()        // 求指数次幂
Math.sqrt()         // 求平方根

案例:

  1、求 10-20 之间的随机数

1 Math.random()  ->  [0, 1)    默认生成[0-1)之间小数
2 公式:Math.floor(Math.random() * (max - min + 1) + min);  // 生成[min,max]之间的随机整数
3 
4 function random(min, max) {
5   return Math.floor(Math.random() * (max - min + 1) + min);
6 }
7 
8 console.log(random(10, 20));         // 调用函数,并输出结果

  2、随机生成颜色 RGB

 1 //  随机生成颜色RGB   [0, 255] 整数
 2 // 定义生成随机数整数的函数
 3 function random(min, max) {
 4    return Math.floor(Math.random() * (max - min + 1) + min);
 5 }
 6 // 定义生成随机颜色的函数
 7 function randomRGB(min, max) {
 8    var color1 = random(min, max);
 9    var color2 = random(min, max);
10    var color3 = random(min, max);
11 
12    return 'rgb(' + color1 + ', ' + color2 + ', ' + color3 + ')';
13 }
14 
15 console.log(randomRGB(0, 255))

  3、模拟实现 max()/min()

 1 // max() 获取参数列表中的最大值;min() 获取参数列表中的最小值;
 2  var MyMath = {                         // 自定义一个对象
 3     max: function () {                  // 在对象内定义一个静态方法 max
 4      var max = arguments[0];
 5      for (var i = 1; i < arguments.length; i++) {
 6        if (max < arguments[i]) {
 7          max = arguments[i];
 8        }
 9      }
10      return max;
11     },
12     min: function () {                  // 在对象内定义一个静态方法 min
13       var min = arguments[0];
14        for (var i = 1; i < arguments.length; i++) {
15          if (min > arguments[i]) {
16            min = arguments[i];
17          }
18        }
19        return min;
20     }
21    };
22 
23 console.log(MyMath.max(10, 1, 100, 20));
24 console.log(MyMath.min(10, 1, 100, 20));
原文地址:https://www.cnblogs.com/niujifei/p/11362736.html