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

Sharing 4 custom functions for generating random numbers in JavaScript_javascript skills

WBOY
Release: 2016-05-16 16:12:24
Original
1322 people have browsed it

The first method

/*
*@desc:生成随机字符串
*@remark:toString方法可以接收一个基数作为参数的原理,这个基数从2到36封顶。如果不指定,默认基数是10进制
*/
function generateRandomAlphaNum(len) {
  var rdmString = "";
  for (; rdmString.length < len; rdmString += Math.random().toString(36).substr(2));
  return rdmString.substr(0, len);
}
Copy after login

The second method

//JS生成GUID函数,类似.net中的NewID(); 
function S4() {
  return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}

function NewGuid() {
  return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}
Copy after login

Third method

//JS生成GUID函数,类似.net中的NewID(); 
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;
}
Copy after login

The fourth method

/*
*@desc:生成随机字符串
*@demo:console.log(ranStr());
*/
;(function(){
  //数字0-9,大写字母,小写字母,ASCII或UNICODE编码(十进制),共62个
  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<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;
})();
Copy after login

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