Example of js method for generating random numbers and js random number instances
Js generates random numbers mainly using the random () method of the built-in Math object. Usage example: Math. random (). It returns a 0 ~ A random number between 1. With this method, it is easy to understand how to generate any random number. For example, we may have the following requirements:
(1) generate a random integer between 0 and 100, then you can:
parseInt(100*Math.random());
Note: because the return values of Math. random () include 0 and 1, it is possible to generate 0 and 100.
(2) generate a random integer between m-n. For example, to generate a random number between 5-15, you can:
parseInt(Math.random()*(15-5+1) + 5);
In general, it is:
ParseInt (Math. random () * (n-m + 1) + m); // generates a random integer between m-n.
In addition, the following two common methods are summarized as needed:
(3) generate a random integer with the specified number of digits
function randomNum(n){ var t=''; for(var i=0;i<n;i++){ t+=Math.floor(Math.random()*10); } return t; }
(4) generate a random integer in the specified range
function randomNum(minNum,maxNum){ switch(arguments.length){ case 1: return parseInt(Math.random()*minNum+1); break; case 2: return parseInt(Math.random()*(maxNum-minNum+1)+minNum); break; default: return 0; break; } }
For example, to generate a random integer between 2-9, then: randomNum (), generate a random integer between 1-22, then: randomNum (22)
The above is the method used to generate random numbers in summary js. I hope it will be helpful for your learning.