JS generates random numbers in a specific range [four situations], and js random numbers
Preface:
JS does not have ready-made functions and can directly generate random numbers within a specified range.
However, it has a function: Math. random (), which can generate a random number of [0, 1.
With this, we can generate a random number within the specified range.
If the range is involved, there is a boundary value problem. In this way, there are four situations:
1) min ≤ r ≤ max (this is 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); // rounding 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); // 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;}
Iv. 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 JS generates a random number in a certain range [four situations] is all the content shared by Alibaba Cloud. I hope you can give us a reference and support for the customer's house.