JS Math.random()方法取得指定范围内的随机整数

Math.floor(Math.random() * (max - min + 1)) + min;

封装成一个函数就可以获得随机数了

        function getRandom(min, max) {
            min = Math.ceil(min);
            max = Math.floor(max);
            return Math.floor(Math.random() * (max - min + 1)) + min;
        }
        console.log(getRandom(2, 5)); //随机生成2-5之间是随机整数
原创文章 24 获赞 13 访问量 1344

猜你喜欢

转载自blog.csdn.net/qq_44755188/article/details/105927250