我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
当前回答
function randomString (strLength, charSet) {
var result = [];
strLength = strLength || 5;
charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
while (strLength--) { // (note, fixed typo)
result.push(charSet.charAt(Math.floor(Math.random() * charSet.length)));
}
return result.join('');
}
这是最干净的了。它也很快,http://jsperf.com/ay-random-string.
其他回答
您可以使用base64:
function randomString(length)
{
var rtn = "";
do {
rtn += btoa("" + Math.floor(Math.random() * 100000)).substring(0, length);
}
while(rtn.length < length);
return rtn;
}
这一个结合了许多给出的答案。
var randNo=Math.floor(Math.random()*100)+2+“”+new Date().getTime()+Math.floof(Math.rrandom()*100)+2+(Math.rand().toString(36).replace(/[^a-zA-Z]+/g,'').substr(0,5));console.log(randNo);
我用了一个月,效果很好。
例如,如果你想要一个随机的DNA序列,你可以循环遍历一个项目数组并递归地将它们添加到字符串变量中:
功能随机DNA(len){len=长度||100var nuc=新阵列(“A”、“T”、“C”、“G”)变量i=0变量n=0s=“”而(i<=len-1){n=数学楼层(Math.random()*4)s+=努克[n]我++}返回s}console.log(随机DNA(5));
//返回随机字母
let alpha = "ABCDEFGHIGKLMNOPQRSTUVWXYZ";
console.log(alpha.charAt(Math.floor(Math.random() * alpha.length)));
短、简单、可靠
返回5个随机字符,而不是此处找到的一些排名最高的答案。
Math.random().toString(36).slice(2, 7);