美文网首页
JavaScript之随机数生成

JavaScript之随机数生成

作者: 荒剑离 | 来源:发表于2020-03-01 22:52 被阅读0次
    • Math.random()
      返回 [0, 1) 之间的随机数。
    • JavaScript 随机整数
      Math.random()Math.floor() 一起使用用于返回随机整数。
    Math.floor(Math.random() * 10);     // 返回 0 至 9 之间的数
    
    • 两个在区间内进行随机数生成的函数

    始终返回 [min, max) 区间中的随机数:

    function getRndInteger(min, max) {
        return Math.floor(Math.random() * (max - min) ) + min;
    }
    

    始终返回[min, max] 区间中的随机数:

    function getRndInteger(min, max) {
        return Math.floor(Math.random() * (max - min + 1) ) + min;
    }
    
    • 补充函数
      parseInt()Math.floor() 结果都是向下取整。
    Math.ceil(Math.random()*10);     // 获取从 1 到 10 的随机整数,取 0 的概率极小。
    
    Math.round(Math.random());       // 可均衡获取 0 到 1 的随机整数。
    
    Math.floor(Math.random()*10);    // 可均衡获取 0 到 9 的随机整数。
    
    Math.round(Math.random()*10);    // 基本均衡获取 0 到 10 的随机整数,其中获取最小值 0 和最大值 10 的几率少一半。
    

    参考资料

    相关文章

      网友评论

          本文标题:JavaScript之随机数生成

          本文链接:https://www.haomeiwen.com/subject/lcgrkhtx.html