Http://www.111cn.net/wy/js-ajax/57062.htm
Math.random () This method is believed to be known to generate random numbers. However, the general reference manual does not show how to use this method to generate random numbers within a specified range. This time I'll give you a detailed introduction to Math.random (), and how to use it to generate a random number within a set range.
W3school's random () tutorial
Definition and usage
The random () method can return a random number between 0 and 1.
Grammar
Math.random ()
return value
A pseudo-random number between 0.0 ~ 1.0.
Instance
In this example, we will get a random number between 0 and 1:
<script type= "Text/javascript" >document.write (Math.random ()); </script>//Output: 0.15246391076246546
How to generate a random number for a specified range value
After reading W3school's tutorial, you should know the basic usage of the Math.random () method.
Rounding processing with parseint (), Math.floor (), or Math.ceil ()
We see that the direct use of the Math.random () method generates a number less than 1, so:
1 math.random ()
The resulting result is a random number less than 5. What we usually want to get is an integer between 0-5, so we need to round up the resulting results to get the integers we expect. parseint (), Math.floor (), and Math.ceil () all can play a rounding role.
1 var randomnum = Math.random (); 2 // 3// 24// 25// 3
As we can see from the code of the test, the effects of parseint () and Math.floor () are the same, and all are taken down to the integer part. So parseint (Math.random () *5,10) and Math.floor (Math.random ()) are all generated random numbers between 0-4, Math.ceil (Math.random ()) is the random number between the generated 1-5.
Generates a specified range of numeric random numbers
So, if you want to generate a random number of 1 to any value, the formula is this:
1 // max-desired maximum value 2 parseint (Math.random () *max,10) +1; 3 Math.floor (Math.random () *max) +1; 4 Math.ceil (Math.random () *max);
If you want to generate random numbers from 0 to any value, this is the formula:
1 // max-desired maximum value 2 parseint (Math.random () * (max+1), ten); 3 Math.floor (Math.random () * (max+1));
If you want to generate random numbers of arbitrary values to any value, this is the formula:
Max-Desired Maximum value
Min-Desired Minimum value
parseint (Math.random () * (max-min+1) +min,10);
Math.floor (Math.random () * (max-min+1) +min);
What do you think? Now it should be clear how to generate you need a random number?! Hope to read this article is helpful for your development! This is the time to be here!
JS Math.random () generates a random number for a specified range of values