js 获取随机数 Math.random()

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>js获取随机数Math.random()</title>
</head>
<body>
<script>
    window.onload = function() {
        // 结果为0-1间的一个随机数(包括0,不包括1)
        var randomNum1 = Math.random();
        //console.log(randomNum1);
        // 函数结果为入参的整数部分。
        var randomNum2 = Math.floor(randomNum1);
        //console.log(randomNum2);
        // 函数结果为入参四舍五入后的整数。
        var randomNum3 = Math.round(randomNum1);
        //console.log(randomNum3);
        // Math.ceil(n); 返回大于等于n的最小整数。
        var randomNum4 = Math.ceil(Math.random() * 10); // 主要获取1到10的随机整数,取0的几率极小。
        //console.log(randomNum4);
        // Math.round(n); 返回n四舍五入后整数的值。
        var randomNum5 = Math.round(Math.random()); // 可均衡获取0到1的随机整数。
        //console.log(randomNum5);
        var randomNum6 = Math.round(Math.random() * 10); // 可基本均衡获取0到10的随机整数,其中获取最小值0和最大值10的几率少一半。
        //console.log(randomNum6);
        // Math.floor(n); 返回小于等于n的最大整数。
        var randomNum7 = Math.floor(Math.random() * 10); // 可均衡获取0到9的随机整数。
        //console.log(randomNum7);
        // 获取最小值到最大值之前的整数随机数
        function GetRandomNum(Min, Max) {
            var Range = Max - Min;
            var Rand = Math.random();
            return (Min + Math.round(Rand * Range));
        }

        var num = GetRandomNum(1, 10);
        //console.log(num);
        //获取n位随机数,随机来源chars
        var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

        function generateMixed(n) {
            var res = "";
            for(var i = 0; i < n; i++) {
                var id = Math.ceil(Math.random() * 35);
                res += chars[id];
            }
            return res;
        }

        var num1 = generateMixed(4);
        console.log(num1);

        //获取n位随机数数字
        function RndNum(n) {
            var rnd = "";
            for(var i = 0; i < n; i++)
                rnd += Math.floor(Math.random() * 10);
            return rnd;
        }

        var num2 = RndNum(4);
        console.log(num2);
    }
</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/longzhoufeng/article/details/80195920