代码之家  ›  专栏  ›  技术社区  ›  Christopher Klewes

JavaScript表达式以在每种情况下生成一个5位数字

  •  52
  • Christopher Klewes  · 技术社区  · 16 年前

    Math.random 仅支持生成 0. 开始浮动。所以它必须介于两者之间 10000 99999 .

    因此,如果它只产生 0.10000 更高,但它也会产生 0.01000

    Math.floor(Math.random()*100000+1)
    

    是否可以在每种情况下(在表达式中!)生成一个5位数字?

    4 回复  |  直到 8 年前
        1
  •  173
  •   Rubens Farias    16 年前

    Math.floor(Math.random()*90000) + 10000;
    
        2
  •  57
  •   Guffa    16 年前

    是的,您可以在任意给定范围内创建随机数:

    var min = 10000;
    var max = 99999;
    var num = Math.floor(Math.random() * (max - min + 1)) + min;
    

    var num = Math.floor(Math.random() * 90000) + 10000;
    
        3
  •  21
  •   miaubiz    16 年前

    如果您想生成一个zipcode,并且只要是5位数字,就可以使用前导零:

    (""+Math.random()).substring(2,7)
    
        4
  •  2
  •   SanS    5 年前

    这个怎么样?

    var generateRandomNDigits = (n) => {
      return Math.floor(Math.random() * (9 * (Math.pow(10, n)))) + (Math.pow(10, n));
    }
    
    generateRandomNDigits(5)
        5
  •  1
  •   Tarek    9 年前

    function getRandomIntInclusive(min, max) {
      min = Math.ceil(min);
      max = Math.floor(max);
      return Math.floor(Math.random() * (max - min + 1)) + min;
    }
    

    有关更多示例和其他用例,请查看 Math.random MDN documentation