Math.random()函数返回0和1之间的伪随机数,可能为0,但总是小于1,[0,1)
公式:[min~max]取随机整数,包含边界值min和max
parseInt(Math.random()*(max-min+1)+min,10);
Math.floor(Math.random()*(max-min+1)+min);
补充:
Math.ceil() 返回大于等于数字参数的最小整数(取整函数),对数字进行上舍入
Math.floor() 返回小于等于数字参数的最大整数,对数字进行下舍入
Math.round() 返回数字最接近的整数,四舍五入
n.toFixed(d) vs Math.round(n)
n.toFixed(d): 按指定d位小数四舍五入,*返回字符串*
Math.round(n): 不能指定小数位数,只能取整
*返回number*
实例
在本例中,我们将取得介于 0 到 1 之间的一个随机数:
代码如下
<script type="text/javascript">
document.write(Math.random());
</script>
// 输出:
0.15246391076246546
如何生成指定范围值的随机数
看完w3school的教程,应该知道Math.random()方法的基本用法了。
利用 parseInt()、Math.floor() 或者 Math.ceil()进行四舍五入处理
我们看到,直接使用Math.random()方法,生成的是一个小于1的数,所以:
代码如下
Math.random()*5
得到的结果是一个小于5的随机数。而我们通常希望得到的是0-5之间的整数,所以我们需要对得到的结果四舍五入处理一下,从而得到我们期望的整数。parseInt()、Math.floor()和Math.ceil()都可以起到四舍五入的作用。
代码如下
var randomNum = Math.random()*5;
alert(randomNum); // 2.9045290905811183
alert(parseInt(randomNum,10)); // 2
alert(Math.floor(randomNum)); // 2
alert(Math.ceil(randomNum)); // 3
由测试的代码我们可以看到,parseInt()和Math.floor()的效果是一样的,都是向下取整数部分。所以parseInt(Math.random()*5,10)和Math.floor(Math.random()*5)都是生成的0-4之间的随机数,Math.ceil(Math.random()*5)则是生成的1-5之间的随机数。
生成指定范围数值随机数
所以,如果你希望生成1到任意值的随机数,公式就是这样的:
代码如下
// max - 期望的最大值
parseInt(Math.random()*max,10)+1;
Math.floor(Math.random()*max)+1;
Math.ceil(Math.random()*max);
如果你希望生成0到任意值的随机数,公式就是这样的:
代码如下
// max - 期望的最大值
parseInt(Math.random()*(max+1),10);
Math.floor(Math.random()*(max+1));
————————————————
原文链接:https://blog.csdn.net/yuanmei1986/article/details/50424441