How to generate a random string of letters and num

2019-04-02 10:18发布

问题:

This question already has an answer here:

  • Random alpha-numeric string in JavaScript? [duplicate] 17 answers

I have been using this code:

function stringGen()
{
    var text = " ";

    var charset = "abcdefghijklmnopqrstuvwxyz0123456789";

    for( var i=0; i < len; i++ )
        text += charset.charAt(Math.floor(Math.random() * charset.length));

    return text;
}

But so far, it has not been working, like at all. What am I doing wrong?

Thank you for your help in advance

回答1:

You missed the parameter len.

function stringGen(len) {
  var text = "";
  
  var charset = "abcdefghijklmnopqrstuvwxyz0123456789";
  
  for (var i = 0; i < len; i++)
    text += charset.charAt(Math.floor(Math.random() * charset.length));
  
  return text;
}

console.log(stringGen(3));

This would give you something like "a1z".



回答2:

A pretty one-liner would be:

Math.random().toString(36).substr(2, length)

Or if you need a str that is longer than 10/11 characters:

function generateRandAlphaNumStr(len) {
  var rdmString = "";
  for( ; rdmString.length < len; rdmString  += Math.random().toString(36).substr(2));
  return  rdmString.substr(0, len);

}


回答3:

Just as alternative:

var len = 20,
    str = '';

while( len-- ) {
    str += String.fromCharCode( 48 + ~~(Math.random() * 42) );
}

console.log( str );


回答4:

Your len variable is undefined. Either pass it in as a parameter, or set it to something.

function stringGen(len)
{
    var text = " ";

    var charset = "abcdefghijklmnopqrstuvwxyz0123456789";

    for( var i=0; i < len; i++ )
        text += charset.charAt(Math.floor(Math.random() * charset.length));

    return text;
}
alert(stringGen(5));

http://jsfiddle.net/rg7Z3/