string 如何在 Javascript 中生成随机的字母和数字字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16106701/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to generate a random string of letters and numbers in Javascript?
提问by Chuck Norris
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
提前谢谢你的帮助
回答by Antony
You missed the parameter len
.
你错过了参数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".
这会给你类似“a1z”的东西。
回答by robahl
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:
或者,如果您需要一个长度超过 10/11 个字符的 str:
function generateRandAlphaNumStr(len) {
var rdmString = "";
for( ; rdmString.length < len; rdmString += Math.random().toString(36).substr(2));
return rdmString.substr(0, len);
}
回答by jAndy
Just as alternative:
作为替代:
var len = 20,
str = '';
while( len-- ) {
str += String.fromCharCode( 48 + ~~(Math.random() * 42) );
}
console.log( str );
回答by SteveP
Your len variable is undefined. Either pass it in as a parameter, or set it to something.
您的 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;
}
alert(stringGen(5));