在开发过程中经常有需要用到随机数的情况,通过JS怎么生成一个随机数呢?
下面两个函数非常关键:
1 2 |
Math.floor() Math.random() |
Math.floor()方法执行向下舍入,既它总是会将数值向下舍入为最接近的整数。
Math.random()方法返回大于等于0小于1的一个随机数。
通过下面的公式我们可以生成我们想要范围的随机数:
1 |
randNum = Math.floor(Math.random() * 最大值 + 最小值); |
当我们想生成一个1到10之间(包括1和10)的随机数,可以这样写:
1 |
var randNum = Math.floor(Math.random() * 10 + 1); |