Math.floor()&&Math.random();
1.用 Math.random() 生成一个随机小数。
2.把这个随机小数乘以 20。
3.用 Math.floor() 向下取整 获得它最近的整数。
解析:Math.floor() 向下取整,所以最终我们获得的结果不可能有 20。这确保了我们获得了一个在0到19之间的整数。
我们先调用 Math.random(),把它的结果乘以20,然后把上一步的结果传给 Math.floor(),最终通过向下取整获得最近的整数。
Math.floor(Math.random() * 20);
在两个数之间生成随机数
在两个数之间产生随机数,先给一个最大值,最小值,在这个区间产生随机数,再和随机小数相乘运算。
Math.floor(Math.random() * (max - min + 1)) + min;
具体代码:
function randomRange(myMin, myMax) {
return Math.floor(Math.random() * (myMax - myMin
+ 1)) + myMin;
}
var myRandom = randomRange(5, 15);
网友评论