demand
Our verification code is a random selection of 62 letters or digits a- Z, A- z, 0-9 and the four letters or digits do not repeat as a verification code
The main idea
1. We need four random letters or numbers, we can use math.random () which is a random number from 0-1. We need random numbers from 0-61 as the random index of the 62 character large string.
2, But math.random () integer decimal will be taken, so we need to use math.round () to round the random number to math.round (math.random ()).
Math.round(math.random ()*61) is the index we need for the large string
4. Secondly, we need a container to hold the 4 random characters and no duplicate strings in it. In this case, we need to use ofIndex===-1, because ofIndex===-1 means that the value does not exist in the container
Packaging function
function fn() {
var str = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM0123456789"
var s = ' '//s is the container containing the four random objectswhile(s.length < 4) {var n = math.round (math.random () * 61) // Set n to a random number that will index STRif(s.i ndexOf (STR [n]) = = = 1) {s + = STR [n] / / not repeat item added to the container}}return s
}
Copy the code
The key point
Math.round(math.random ()*(m-n)+n; math.round (math.random ()*(m-n)+n
If (STR [n])===-1 if (STR [n])===-1 if (STR [n])===-1 if (STR [n])===-1 if (STR [n])===-1