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; 

过程分析:

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);
// 用户输入
const min = parseInt(prompt("输入最小值: "));
const max = parseInt(prompt("输入最大值: "));
// 生成随机数
const a = Math.floor(Math.random() * (max - min + 1)) + min;
// 显示随机数
document.write(`${min} 到 ${max} 的随机数:${a}`);
尝试一下 »

一个在线的随机数生成器:https://c.runoob.com/front-end/6680/

原文链接:http://www.cnblogs.com/starof/p/4988516.html