Math.random()

1.Math.random() 随机函数

Math.random()是令系统随机选取大于等于 0.0 且小于 1.0 的随机数

alert(Math.random())取值在[0,1)

2.Math.round(数字) 四舍五入

alert(Math.round(3.2)) 弹出3

alert(Math.round(Math.random()))  弹出0或者1  // 0/1

0~10        alert(Math.round(Math.random()*10))  弹出0~10   

5~10        alert(Math.round(Math.random()*5+5))  弹出5~10  

10~20      alert(Math.round(Math.random()*10+10))  弹出10~20  

20~100    alert(Math.round(Math.random()*80+20))  弹出20~100

推理

x~y           alert(Math.round(Math.random()*(y-x)+x))  弹出x~y

0~x          alert(Math.round(Math.random()*x))             弹出x0~x

1~x           alert(Math.ceil(Math.random()*x))                弹出1~x

验证

<script>
var x=42;
var y=45;
alert(Math.round(Math.random()*(y-x)+x))
</script>

弹出 42,43,44,45

原文地址:https://www.cnblogs.com/Xuman0927/p/5461142.html