js randomly generated

math.random it to generate a pseudo-random number, after which they treated the job.
 

w3school of random () Tutorial
definition and usage

random () method returns a random number ranging between 0 and 1.
grammar

Math.random()

return value

A pseudo-random number between 0.0 and 1.0.
Examples

Take 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 to specify a range of values

Using parseInt (), Math.floor () or Math.ceil () rounded off

  Directly Math.random () method, generated is a number less than 1,

Math.random()*5
The result is a random number less than 5. And we usually want to get is an integer between 0-5 result by rounding get integer. 
parseInt (), the Math. Floor ()
and the Math. ceil () can play a role in rounding.
var randomNum = Math.random()*5;
alert(randomNum); // 2.9045290905811183 
alert(parseInt(randomNum,10));  // 2
alert(Math.floor(randomNum));   // 2
alert(Math.ceil(randomNum));    // 3

  Note: the parseInt () and . The Math Floor () effect is the same, are rounded down integer part .

    Therefore, the parseInt (Math.random () * 5,10) and the Math .floor (Math.random () *. 5) are generated by a random number between 0-4 ,
    the Math. Ceil (Math.random (). 5 * ) is generated by a random number between 1-5 .

Generating a random number value specified range

So, if you want to generate a random number to any value, the formula is this:

// max - a desired maximum value 
the parseInt (Math.random () * max, 10) + 1'd ;
Math.floor(Math.random()*max)+1;
Math.ceil(Math.random()*max);

If generation 0 to any value of a random number:

// max - a desired maximum value 
the parseInt (Math.random () * (+ max. 1), 10 );
Math.floor(Math.random()*(max+1));

If the generated arbitrary value to an arbitrary value of the random number:

// max - maximum desired 
// min - minimum desired 
the parseInt (Math.random () * (max-min +. 1) + min, 10 );
Math.floor(Math.random()*(max-min+1)+min);

 

Guess you like

Origin www.cnblogs.com/whoamimy/p/12588433.html