Share the four functions implemented by JS to generate random numbers
This article mainly introduces the sharing of four functions for generating random numbers implemented by JS. This article provides the implementation code directly. If you need it, refer
Method 1
The Code is as follows:
/*
* @ Desc: generates a random string.
* @ Remark: the toString method can receive a base number as a parameter. This base number is capped from 2 to 36. If not specified, the default base is in decimal format.
*/
Function generateRandomAlphaNum (len ){
Var rdmString = "";
For (; rdmString. length <len; rdmString + = Math. random (). toString (36). substr (2 ));
Return rdmString. substr (0, len );
}
Method 2
The Code is as follows:
// JS generates the GUID function, similar to NewID () in. net ();
Function S4 (){
Return (1 + Math. random () x 0x10000) | 0). toString (16). substring (1 );
}
Function NewGuid (){
Return (S4 () + S4 () + "-" + S4 () + "-" + S4 () + "-" + S4 () + "-" + S4 () + S4 () + S4 ());
}
Method 3
The Code is as follows:
// JS generates the GUID function, similar to NewID () in. net ();
Function newGuid (){
Var guid = "";
For (var I = 1; I <= 32; I ++ ){
Var n = Math. floor (Math. random () * 16.0). toString (16 );
Guid + = n;
If (I = 8) | (I = 12) | (I = 16) | (I = 20 ))
Guid + = "-";
}
Return guid;
}
Method 4
The Code is as follows:
/*
* @ Desc: generates a random string.
* @ Demo: console. log (ranStr ());
*/
; (Function (){
// Numbers 0-9, uppercase letters, lowercase letters, ASCII or UNICODE (decimal), 62 in total
Var charCodeIndex = [[97,122], [], [];
Var charCodeArr = [];
Function getBetweenRound (min, max ){
Return Math. floor (min + Math. random () * (max-min ));
};
Function getCharCode (){
For (var I = 0, len = 3; I <len; I ++ ){
Var thisArr = charCodeIndex [I];
For (var j = thisArr [0], thisLen = thisArr [1]; j <= thisLen; j ++ ){
CharCodeArr. push (j );
}
}
}
Function ranStr (slen ){
Slen = slen | 20;
CharCodeArr. length <62 & getCharCode ();
Var res = [];
For (var I = 0; I <slen; I ++ ){
Var index = getBetweenRound (0, 61 );
Res. push (String. fromCharCode (charCodeArr [index]);
}
Return res. join ('');
};
This. ranStr = ranStr;
})();