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 of verification codes.
Math.random() function returns a pseudo-random number between 0 and 1, which may be 0 but is always less than 1, [0,1)
Generate n-m, integers including n but not m:
The first step is to calculate the value of m-n, assuming it is equal to w
The second step Math.random()*w
Step 3 Math.random()*w n
Step 4 parseInt(Math.random()*w n, 10)
Generate n-m, an integer that does not contain n but contains m:
The first step is to calculate the value of m-n, assuming it is equal to w
The second step Math.random()*w
Step 3 Math.random()*w n
Step 4 Math.floor(Math.random()*w n) 1
Generate n-m, an integer excluding n and m:
The first step is to calculate the value of m-n-2, assuming it is equal to w
The second step 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 n-m, random numbers containing n and m:
The first step is to calculate the value of m-n, assuming it is equal to w
The second step 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 between 800-1500, including 800 but not including 1500
Math.ceil() returns the smallest integer (rounding function) that is greater than or equal to the numeric parameter, and rounds the number up
Math.floor() returns the largest integer less than or equal to the numeric parameter, rounding the number down
Math.round() returns the number to the nearest integer, rounded