function fn(x, y) {
return Math.floor(Math.random() * (y - x + 1)) + x
}
console.log(fn(10, 20));
要生成x~y之间的随机整数,我们需要以下两个步骤:
生成介于0和1之间的随机小数。
在JavaScript中,Math.random()方法返回一个大于等于0且小于1的浮点数。
console.log(Math.random());//0到0.9999...之间的随机数
将随机小数转换成介于x和y之间的随机整数。
假设我们要求的范围是1~10之间的整数
Math.floor的作用是向下取整
console.log(Math.floor(Math.random()*10));
//那么我们在Math.random后面乘以10,就可以得出0到10之间的整数(不包含10),即0~9
由于我们需要的是1~10之间的整数,不是0~10(不包含10)之间的整数
因此我们要是结果为(1+0)~(1+9),即1~10之间的整数
0~10的时候 Math.random()*11
0~20的时候 Math.random()*21
0~30的时候 Math.random()*31
0~x 的时候 Math.random()*(x+1)
即console.log(Math.floor(Math.random()*(10+1)));
返回x~y之间的随机数
0~10的时候,返回 (0~10)+0
10~20的时候,返回 (0~10)+10
20~30的时候,返回 (0~20)+20
10~30的时候,返回 (0~20)+10
x~y 的时候,返回 (0~y-x)+x
即console.log(Math.floor(Math.random() * (y - x + 1)+x));
那么完整的代码:
function fn(x, y) {
return Math.floor(Math.random() * (y - x + 1)) + x
}
console.log(fn(10, 20));