Math.random():生成一个范围为[0:1)的伪随机数。
常用的随机数:
1)min ≤ r ≤ max
2)min ≤ r < max
3) min < r ≤ max
4)min < r < max
方法:
一、min ≤ r ≤ max
function RandomNumBoth(Min,Max){ var Range = Max - Min; var Rand = Math.random(); var num = Min + Math.round(Rand * Range); //四舍五入 return num; }
二、min ≤ r < max
function RandomNum(Min, Max) { var Range = Max - Min; var Rand = Math.random(); var num = Min + Math.floor(Rand * Range); //舍去 return num; }
三、min < r ≤ max
function RandomNum(Min, Max) { var Range = Max - Min; var Rand = Math.random(); if(Math.round(Rand * Range)==0){ return Min + 1; } var num = Min + Math.round(Rand * Range); return num; }
四、min < r < max
function RandomNum(Min, Max) { var Range = Max - Min; var Rand = Math.random(); if(Math.round(Rand * Range)==0){ return Min + 1; }else if(Math.round(Rand * Max)==Max) { index++; return Max - 1; }else{ var num = Min + Math.round(Rand * Range) - 1; return num; } }