当前位置:   article > 正文

JS生成随机数_js 40以内随机数

js 40以内随机数

随机数

  1. Math.random() 为0到1之间的随机数(包括0,不包括1)[0, 1)
  2. Math.round(n) 为n四舍五入后的整数
  3. Math.ceil(n) 为大于等于n的最小整数
  4. Math.floor(n) 为小于等于n的最大整数

实例

例1:创建一个长度为10,元素范围为1到10之间的数组

 {
      const arr = []
      for(let i = 0; i < 10; i++){
         const a = Math.random()*10 + 1;
         arr.push(Math.floor(a))
      }
      console.log(arr);
 }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

例2:创建一个长度为100,元素范围为31到60之间的数组(包括31也包括60)

  const arr = []
  for(let i = 0; i < 100; i++){
     const a = Math.random()*29 + 31;
     arr.push(Math.round(a))
  }
  console.log(arr);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

min ≤ n ≤ max : Math.round(Math.random()*(max-min)+min)

例2:创建一个长度为100,元素范围为31到60之间的数组(包括31不包括60)

 {
      const arr = []
      for(let i = 0; i < 100; i++){
         const a = Math.random()*29 + 31;
         arr.push(Math.floor(a))
      }
      console.log(arr);
 }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

min ≤ n ≤ max : Math.floor(Math.random()*(max-min)+min)

例3:创建一个长度为100,元素范围为31到60之间的数组(不包括31包括60)

      function randomFill() {
        const range = Math.round(Math.random()*29);
        let num = range + 31;
        if(range === 0){
          return num + 1
        }else{
          return num
        }
      }

      const arr = []
      for(let i = 0; i < 100; i++){
         const num = randomFill();
         arr.push(num)
      }
      console.log(arr);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

例4:创建一个长度为100,元素范围为31到60之间的数组(不包括31不包括60)

    function randomFill() {
        const range = Math.round(Math.random()*29);
        let num = range + 31;
        if(range === 0){
          return num + 1
        }else if(range === 29){
          return num - 1
        }else{
          return num
        }
      }

      const arr = []
      for(let i = 0; i < 100; i++){
         const num = randomFill();
         arr.push(num)
      }
      console.log(arr);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/54521
推荐阅读
相关标签
  

闽ICP备14008679号