This article mainly introduces how javascript automatically generates random strings containing numbers and characters, involving Math. random () and Math. the usage skills of floor () functions. if you need them, refer to the examples in this article to illustrate how javascript automatically generates random strings containing numbers and characters. Share it with you for your reference. The details are as follows:
Math. random () and Math. floor () are mainly used here.
Math. random () -- Returns a pseudo-random number between 0 and 1, which may be 0, but always less than 1)
Math. floor () -- round down and remove the value after the small number
How to implement random multiple digits:
The code is as follows:
/**
*
* Randomly generate numbers
*
* @ Param num: number of digits generated
*/
Function randomNumber (num ){
Return ''+ Math. floor (Math. random () * num );
}
Javascript randomly generated characters
The following examples are random characters in the random A-Z/a-z range
The code is as follows:
/**
*
* Random generation
*
* @ Param data json data example: {"start": 0, "end": 2, "number": 5, "upper": true}
* @ Param start subscript
* @ Param end subscript
* @ Param number: number of digits generated
* @ Param upper whether to use uppercase letters is lowercase by default
*/
Function randomLetter (data ){
Var letterData = "";
Var lowercase = new Array ("a", "B", "c", "d", "e", "f", "g", "h ", "I", "g", "k", "l", "m", "n", "o", "p", "q", "r ", "s", "t", "u", "v", "w", "x", "y", "z ");
Var uppercase = new Array ("A", "B", "C", "D", "E", "F", "G", "H ", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R ", "S", "T", "U", "V", "W", "X", "Y", "Z ");
Var start = data. start;
Var end = data. end;
Var number = data. number;
Var upper = data. upper;
Var length = end-start;
For (var I = 0; I <number; I ++ ){
Var index = Math. floor (Math. random () * length) + start;
Var letter = "";
If (upper ){
Letter = uppercase [index];
} Else {
Letter = lowercase [index];
}
LetterData + = letter;
}
Return letterData;
}
Reference:
The code is as follows:
Alert (new Date (). Format ("yyyy-MM-dd hh: mm: ss "));
I hope this article will help you design javascript programs.