js常用内容汇总

版权声明:任何形式的转载请注明出处 https://blog.csdn.net/weixin_42259823/article/details/85631106

js生成随机数

Math.ceil();  //向上取整。

Math.floor();  //向下取整。

Math.round();  //四舍五入。

Math.random();  //0.0 ~ 1.0 之间的一个伪随机数。【包含0不包含1】 //比如0.8647578968666494

Math.ceil(Math.random()*10);      // 获取从1到10的随机整数 ,取0的概率极小。

Math.round(Math.random());   //可均衡获取0到1的随机整数

Math.floor(Math.random()*10);  //可均衡获取0到9的随机整数

扫描二维码关注公众号,回复: 4817175 查看本文章

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。所以头尾的分布区间只有其他数字的一半。

//生成从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; 
    } 
}

猜你喜欢

转载自blog.csdn.net/weixin_42259823/article/details/85631106