Home > Web Front-end > JS Tutorial > body text

Sharing of 4 functions for generating random numbers implemented in JS_Basic knowledge

WBOY
Release: 2016-05-16 16:14:34
Original
1121 people have browsed it

The first method

Copy code The code is as follows:

/*
*@desc: Generate random string
*@remark: The toString method can receive a base as a parameter, and the base is capped from 2 to 36. If not specified, the default base is decimal
*/
function generateRandomAlphaNum(len) {
var rdmString = "";
for (; rdmString.length < len; rdmString = Math.random().toString(36).substr(2));
Return rdmString.substr(0, len);
}

The second method

Copy code The code is as follows:

//JS generates a GUID function, similar to NewID() in .net;
function S4() {
Return (((1 Math.random()) * 0x10000) | 0).toString(16).substring(1);
}

function NewGuid() {
Return (S4() S4() "-" S4() "-" S4() "-" S4() "-" S4() S4() S4());
}

The third method

Copy code The code is as follows:

//JS generates a 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;
}

The fourth method

Copy code The code is as follows:

/*
*@desc: Generate random string
*@demo:console.log(ranStr());
*/
;(function(){
//Numbers 0-9, uppercase letters, lowercase letters, ASCII or UNICODE encoding (decimal), 62 in total
var charCodeIndex = [[48,57],[65,90],[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           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             var index = getBetweenRound(0,61);
              res.push(String.fromCharCode(charCodeArr[index]));
}
           return res.join('');
};

this.ranStr = ranStr;
})();

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!