根据需要生成自己的随机数,一般用简单的随机数就可以了
一、随机数
生成随机整数,要求范围内的每个整数概率相同
比如说,随机生成0-10内的整数
这样写有问题吗:Math.round(Math.random() * 10)
四舍五入会导致首尾两数的概率为其它数的一半,如下图所示:
0到1之间
Math.random(0,1)
1 到 10 之间
Math.floor((Math.random() * 10) + 1)
min(包含)~ max(不包含)之间
Math.floor(Math.random() * (max - min)) + min
min(包含)~ max(包含)之间
Math.floor(Math.random() * (max - min + 1)) + min
验证下随机数的概率
二、时间戳
Date.now()
三、时间戳+随机数
Date.now() + +Math.random().toFixed(3)