JavaScript generates random numbers of 4 kinds of custom functions to share _javascript tips

Source: Internet
Author: User

The first of these methods

*
* @desc: Generate a random string
* @remark: The ToString method can receive a cardinality as a parameter of the principle, which is capped from 2 to 36. If not specified, the default cardinality is 10
/function Generaterandomalphanum (len) {
  var rdmstring = "";
  for (; rdmstring.length < len; rdmstring + = Math.random (). toString (2));
  Return rdmstring.substr (0, Len);
}

The second method

JS generates a GUID function, similar to the NEWID in. NET (); 
function S4 () {return
  ((1 + math.random ()) * 0x10000) | 0). toString (+). substring (1);
}

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

The third method

JS generates a GUID function, similar to the NEWID in. NET (); 
function NewGuid () {
  var guid = ' ";
  for (var i = 1; I <= i++) {
    var n = math.floor (Math.random () * 16.0). toString ();
    GUID + N;
    if ((i = = 8) | | (i = = 12) | | (i = = 16) | | (i = =))
      GUID = + "-";
  }
  return GUID;
}

Fourth method

*
* @desc: Generate random string
* @demo: Console.log (Ranstr ());
*
/;(function () {
  //number 0-9, uppercase letters, lowercase letters, ASCII or Unicode encoding (decimal), total 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 | |
    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;
}) ();

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.