This article describes how to generate random numbers in JavaScript. For more information, see [n, m ].
I. prerequisites
Math. ceil (); // rounded up. Math. floor (); // round down. Math. round (); // rounding. Math. random (); // 0.0 ~ A pseudo-random number between 1.0. [0 does not contain 1] // for example, 0.8647578968666494Math.ceil (Math. random () * 10); // gets a random integer from 1 to 10, with a very low probability of getting 0. Math. round (Math. random (); // You Can evenly obtain random integers ranging from 0 to 1. Math. floor (Math. random () * 10); // You Can evenly obtain random integers ranging from 0 to 9. Math. round (Math. random () * 10); // Obtain a random integer ranging from 0 to 10 in basic balancing. the probability of obtaining a minimum value of 0 and a maximum value of 10 is less than half.
Because the result ranges from 0 ~ 0.4 is 0, 0.5 to 1.4 is 1... 8.5 to 9.4 is 9, 9.5 to 9.9 is 10. Therefore, the distribution interval at the beginning and end is only half of other numbers.
2. Generate a random integer of [n, m]
Function: generate a random integer of [n, m.
It is useful when js generates a verification code or randomly selects an option ..
// Generate the random number function randomNum (minNum, maxNum) from minNum to maxNum {switch (arguments. length) {case 1: return parseInt (Math. random () * minNum + 1, 10); break; case 2: return parseInt (Math. random () * (maxNum-minNum + 1) + minNum, 10); break; default: return 0; break ;}}
Process Analysis:
Math. random () generates the number of [0, 1), so Math. random () * 5 generates the number of {0, 5.
We usually expect to get an integer, so we need to process the result.
All parseInt (), Math. floor (), Math. ceil (), and Math. round () can be integers.
The parseInt () and Math. floor () results are rounded down.
Therefore, Math. random () * 5 generates random integers of [0, 4.
Therefore, the random number of [1, max] is generated. the formula is as follows:
// Max-the expected maximum value parseInt (Math. random () * max, 10) + 1; Math. floor (Math. random () * max) + 1; Math. ceil (Math. random () * max );
Therefore, a random number from [0, max] to any number is generated. the formula is as follows:
// Max-the expected maximum value parseInt (Math. random () * (max + 1), 10); Math. floor (Math. random () * (max + 1 ));
To generate a random number for [min, max], the formula is as follows:
// Max-the expected maximum value // min-the expected minimum value parseInt (Math. random () * (max-min + 1) + min, 10); Math. floor (Math. random () * (max-min + 1) + min );
The above is a comprehensive analysis of the random numbers generated by js. it is very detailed and I hope it will help you.