Use the js Math. random () function to generate random numbers between n and m.

Abstract:

This article explains how to use js to generate random numbers between n and m. The main purpose is to prepare for later JavaScript code generation.

The Math. random () function returns a pseudo-random number between 0 and 1, which may be 0, but always less than 1)

Generate n-m, which contains n but does not contain an integer of m:

The first step is to calculate the m-n value, assuming that it is equal to w

Step 2 Math. random () * w

Step 3 Math. random () * w + n

Step 4 parseInt (Math. random () * w + n, 10)

Generate n-m, which does not contain n but contains an integer of m:

The first step is to calculate the m-n value, assuming that it is equal to w

Step 2 Math. random () * w

Step 3 Math. random () * w + n

Step 4 Math. floor (Math. random () * w + n) + 1

Generate n-m, excluding Integers of n and m:

The first step is to calculate the value of the m-n-2, assuming that it is equal to w

Step 2 Math. random () * w

Step 3 Math. random () * w + n + 1

Step 4 Math. round (Math. random () * w + n + 1) or Math. ceil (Math. random () * w + n + 1)

Generate a random number of n-m, including n and m:

The first step is to calculate the m-n value, assuming that it is equal to w

Step 2 Math. random () * w

Step 3 Math. random () * w + n

Step 4 Math. round (Math. random () * w + n) or Math. ceil (Math. random () * w + n)

Example:

Generate a random integer of 800 to 1500, including, but not

The Code is as follows:

1500-800 = 700

Math. random () * 700

Var num = Math. random () * 700 + 800;

Num = parseInt (num, 10 );

Only four simple steps are required.

Supplement:

Math. ceil () returns the smallest integer greater than or equal to the number parameter (take the entire function), rounded up the number

Math. floor () returns the largest integer smaller than or equal to the number parameter, and homes the number

Math. round () returns the nearest integer to the number, rounding