Summary:
This article explains how to use JS to generate random numbers between N and M, the main purpose is to prepare for the later JS generation verification code.
The Math.random () function returns a pseudo-random number between 0 and 1, which may be 0, but is always less than 1,[0,1)
Generates an integer that contains n but does not contain m: n-m
The first step is to calculate the value of the m-n, assuming equal to W
Step two math.random () *w
Step three math.random () *w+n
Fourth Step parseint (Math.random () *w+n, 10)
Generate N-M, not containing n but an integer with M:?
The first step is to calculate the value of the m-n, assuming equal to W
Step two math.random () *w
Step three math.random () *w+n
Fourth Step Math.floor (Math.random () *w+n) + 1
Generate N-m, with no integers of N and M:
The first step is to calculate the value of the m-n-2, assuming equal to W
Step two math.random () *w
Step three math.random () *w+n +1
Fourth Step Math.Round (Math.random () *w+n+1) or Math.ceil (Math.random () *w+n+1)
Generate N-M, containing random numbers of N and M:
The first step is to calculate the value of the m-n, assuming equal to W
Step two math.random () *w
Step three math.random () *w+n
Fourth Step Math.Round (Math.random () *w+n) or Math.ceil (Math.random () *w+n)
Example:
Generates a random integer of 800-1500 that contains 800 but does not contain 1500
- 1500-800 = 700
- Math.random () *700
- var num = math.random () *700 + 800;
- num = parseint (num, 10);
It takes just four simple steps to complete.
Add:
Math.ceil () returns the smallest integer greater than or equal to the number parameter (rounding function) to round the number
Math.floor () returns the largest integer less than or equal to the number parameter, rounding the number down
Math.Round () returns the nearest integer of the number, rounded
JavaScript generates random integers n to M