当前位置:   article > 正文

Math对象随机数方法—random()_math.random()获取随机数字

math.random()获取随机数字

Math 对象中方法的使用

  • 【1】Math.random() 获取一个随机数,默认取值为0-1(不包含1)
  • 【2】Math.round(值) 四舍五入得到一个整数
  • 【3】Math.ceil(值) 向上取整
  • 【4】Math.floor(值) 向下取整
  • 【5】Math.pow(值) 取幂
  • 【6】Math.sqrt(值) 开平方
  • 【7】Math.max(值) 返回最大值
  • 【8】Math.min(值) 返回最小值
  • 【9】Math.abs(值) 取绝对值
  • 【10】Math.PI得到一个圆周率 3.141592653589793

随机数random()

1、Math对象里面随机数方法,random()返回一个随机的小数 0 <= x < 1;
2、这个方法里面不跟参数;
3、验证代码:

    console.log(Math.random())
  • 1

4、如果得到随机整数,并且包含这2个整数:

    Math.floor(Math.random()*(max - min + 1)) + min;
  • 1

例:


    function getRandom(min, max) {
      return Math.floor(Math.random() * (max - min + 1)) + min
    }
    console.log(getRandom(1, 100))
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

在这里插入图片描述
5、拓展:随机点名


   //封装一个随机数函数
    function getRandom(min, max) {
      return Math.floor(Math.random() * (max - min + 1)) + min
    }
    
    var arrName = ["小白", "小红", "小蓝", "小妞", "小牛", "小黑", "小明"]
    console.log(arrName[getRandom(0, arrName.length - 1)])
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

6、补充一点

<script>
    /*
        随机数:Math.random()
        得到的是一个0-1(包含0但是不包含1)的随机数
        0*10-1*10---0-10 不包含10

        得到一个0-10的随机整数数 Math.random()*11 在取整

        得到一个 10-30的随机整数
        0-1 --- 0*31-1*31---0+10-30+10 --10-40
        0*21-1*21--0+10-20+10 ----10-30
    */

    // console.log(parseInt(Math.random() * 11));
    // console.log(parseInt(Math.random() * 21 + 10));

    // 30 到 80 之间的随机数 *51+30
    // console.log(parseInt(Math.random() * 51 + 30));

    // 编写一个函数,求任意两个数值之间的随机数,并返回
    function randomNum(n, m) {
      // (0-1)*191--(0-191)+10--10-201 191 = 200-10 + 1
      // return parseInt(Math.random() * 191 + 10)

      // 判断两个参数的大小
      var max, min;
      max = n > m ? n : m;
      min = n < m ? n : m;
      // (0-1)*6--(0-6)+10--10--16 6 = 15-10- +1
      return parseInt(Math.random() * (max - min + 1) + min);
      // (0-1)*(-7)-7--0--18--25
    }
    console.log(randomNum(27, 20));


  </script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/54546
推荐阅读
相关标签
  

闽ICP备14008679号