This article describes how to use javascript to obtain random numbers of four digits or letters. For more information, see the following section.
A simple method is to randomly extract four non-repeating characters from numbers and letters.
The code example is as follows:
Function only (ele, arr) {if (arr. length = 0) {return true ;}for (var j = 0; jThe above Code meets our requirements. The following describes the implementation process of the above Code.
I. Code comments:
1. function only (ele, arr) {}, this function can be used to determine whether the specified index has been used, and random numbers are placed repeatedly.
2. if (arr. length = 0) {}, if the array is empty, it indicates that it cannot be repeated. true is returned.
3. for (var j = 0; j5. (function () {}) (arr), an self-executed function, and passing a parameter.
6. var randNum = null: declare a variable and assign the initial value to null to store randomly generated array indexes.
7. var old = [], create an empty array to store the existing array index values.
8. var str = "", creates an empty string to store the generated random number.
9. function done () {}, which can be used to obtain a random number.
10. randNum = Math. floor (Math. random () * 14) to obtain the index value of the array.
11. if (only (randNum, old )){
Str = str + arr [randNum];
Old. push (randNum );
} To determine whether it has been used. If not, obtain the array element, append it to the str string, and append the index value to the old array.
12. else {done ();
}, If you have already used it, obtain it again. Here we use recursion.
13. for (var index = 0; index <4; index ++ ){
Done ();
}, Use the for loop to obtain four random numbers.
From: http://www.softwhy.com/forum.php? Mod = viewthread & tid = 16493.