Preface:
JS does not have ready-made functions and can directly generate random numbers in a specified range.
But it has a function: Math.random() This function can generate a random number of [0,1).
Using it, we can generate random numbers in a specified range.
If the scope is involved, there is a problem of boundary value. This includes four situations:
1) min ≤ r ≤ max (usually this is more common)
2) min ≤ r < max
3) min < r ≤ max
4) min < r < max
1. min ≤ r ≤ max
function RandomNumBoth(Min,Max){ var Range = Max - Min; var Rand = Math.random(); var num = Min + Math.round(Rand * Range); //Round return num;}2. min ≤ r <max
function RandomNum(Min, Max) { var Range = Max - Min; var Rand = Math.random(); var num = Min + Math.floor(Rand * Range); //Save return num;}3. 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;}4. 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; } }The above article JS generates a random number in a certain range [Detailed explanation of the four situations] is all the content I share with you. I hope it can give you a reference and I hope you can support Wulin.com more.