js 生成随机数

wylc123 1年前 ⋅ 1695 阅读

js 可以使用 Math(算数) 对象来实现随机数的生成。

需要了解的 Math 对象方法

方法 描述
ceil(x) 对数进行上舍入,即向上取整。
floor(x) 对 x 进行下舍入,即向下取整。
round(x) 四舍五入。
random() 返回 0 ~ 1 之间的随机数,包含 0 不包含 1。

一些实例说明:

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 的几率少一半。

因为结果在 0~0.4 为 0,0.5 到 1.4 为 1,8.5 到 9.4 为 9,9.5 到 9.9 为 10。所以头尾的分布区间只有其他数字的一半。


生成 [n,m] 的随机整数

函数功能:生成 [n,m] 的随机整数。

在 js 生成验证码或者随机选中一个选项时很有用。

//生成从minNum到maxNum的随机数
function randomNum(minNum,maxNum){ 
    switch(arguments.length){ 
        case 1: 
            return parseInt(Math.random()*minNum+1,10); 
        break; 
        case 2: 
            return parseInt(Math.random()*(maxNum-minNum+1)+minNum,10); 
        break; 
            default: 
                return 0; 
            break; 
    } 
} 

相关文章推荐

全部评论: 0

    我有话说: