A summary of the methods of generating random numbers by JS
JS generates random numbers primarily using the random () method of the built-in math object. Usage such as: Math.random (). It returns a random number between 0 and 1. With such a method, it is understandable to generate arbitrary random numbers. For example, in practice we may have the following needs:
(1) generate a random integer between 0-100, then you can:
- parseint (100*math.random ());
Note: Because the return value of Math.random () is 0 and 1, there is the possibility of generating 0 and 100.
(2) generate a random integer from M-n, for example to generate a random number between 5-15, you can:
- parseint (Math.random () * (15-5+1) + 5);
The summary is:
parseint (Math.random () * (n-m+1) +m);//Generate a random integer from M-n
In addition, according to the need www.phpernote.com summed up the other two commonly used methods, as follows:
(1) generating a random integer of 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;
- }
(2) Generate random integers 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 (2,9), generates a random integer between 1-22, then: Randomnum (22)
This article original address: http://www.daimajiayuan.com/sitejs-17200-1.html
A summary of the methods of generating random numbers by JS [Favorites]