js生成[n,m]的随机数公式,存入一个数组中,并排序

一 、预备知识

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的随机整数

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

二、实现随机取整函数功能

    实现原理:判断随机取整范围的最大值和最小值,默认是0。

    使用范围:在js生成验证码或者随机选中一个选项

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

   过程分析:

        Math.random()生成[0,1)的数,所以

        Math.random()*5生成{0,5)的数。

        通常期望得到整数,所以要对得到的结果处理一下。

        parseInt(),Math.floor(),Math.ceil()和Math.round()都可得到整数。

        parseInt()和Math.floor()结果都是向下取整。

        所以Math.random()*5生成的都是[0,4] 的随机整数。

        所以生成[1,max]的随机数,公式如下:

// max - 期望的最大值
parseInt(Math.random()*max,10)+1;
Math.floor(Math.random()*max)+1;
Math.ceil(Math.random()*max);

         所以生成[0,max]到任意数的随机数,公式如下:

// max - 期望的最大值
parseInt(Math.random()*(max+1),10);
Math.floor(Math.random()*(max+1));

         所以希望生成[min,max]的随机数,公式如下:

// max - 期望的最大值
// min - 期望的最小值
parseInt(Math.random()*(max-min+1)+min,10);
Math.floor(Math.random()*(max-min+1)+min);

实现一个小demo 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
</body>
<script>
    //随机取10-100中三个值,存入一个数组,并排序
    function getRandom(minNum, maxNum) {
        switch (arguments.length) {
            case 1:
                return Math.floor(Math.random() * minNum);
                break;
            case 2:
                return Math.floor(Math.random() * (maxNum - minNum + 1) + minNum);
                break;
            default:
                return 0;
                break;
        }
    }
    //声明一个空数组
    var array = [];
    //获取10-100之间的10个随机数,并存入数组
    for (var i = 0; i < 10; i++) {
        array.push(getRandom(10, 100));
    }
    //升序排列
    alert(array.sort(function (x, y) {
        return x - y;
    }));
    //降序排列
    alert(array.sort(function (x, y) {
        return y - x;
    }))
</script>

</html>

本文作者王小熊,因知识本身在变化,作者也在不断学习成长,文章内容也不定时更新,为避免误导读者,方便追根溯源,请诸位转载注明出处。

有问题欢迎与我讨论,共同进步。 

如果觉得本文对您有帮助~可以微信支持一下:





    

猜你喜欢

转载自blog.csdn.net/m13302979400/article/details/80637438