我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
当前回答
这是我用过的。这是一对夫妇的组合。我在循环中使用它,它生成的每个ID都是唯一的。它可能不是5个字符,但它保证是唯一的。
var newId =
"randomid_" +
(Math.random() / +new Date()).toString(36).replace(/[^a-z]+/g, '');
其他回答
一个衬垫[a-z]:
String.fromCharCode(97 + Math.floor(Math.random() * 26))
这里有一种不同的方法,按基数固定长度,不使用RegExp替换lack(基于@bendytree的答案);
function rand(base) {
// default base 10
base = (base >= 2 && base <= 36) ? base : 10;
for (var i = 0, ret = []; i < base; i++) {
ret[i] = ((Math.random() * base) | 0).toString(base)
// include 0-9a-zA-Z?
// [Math.random() < .5 ? 'toString' : 'toUpperCase']();
}
return ret.join('');
}
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.
//可以将7更改为2以获得更长的结果。让r=(Math.random()+1).toString(36).substring(7);console.log(“随机”,r);
注:上述算法有以下缺点:
它将生成0到6个字符之间的任何字符,这是因为字符串化浮点时会删除尾随零。这在很大程度上取决于用于字符串化浮点数的算法,这非常复杂。(请参阅论文“如何准确打印浮点数字”。)根据实现的不同,Math.random()可能会产生可预测的(“看起来随机”但不是真正随机的)输出。当需要保证唯一性或不可预测性时,生成的字符串不适合。即使它产生了6个统一的随机、不可预测的字符,由于生日悖论,在只产生了大约50000个字符串之后,你也可以看到重复的字符。(平方英尺(36^6)=4656)
这是第一个答案的测试脚本(谢谢@csharptest.net)
该脚本运行makeid()100万次,如您所见,5不是一个非常独特的脚本。以10的字符长度运行它是非常可靠的。我已经运行了大约50次,还没有看到重复的:-)
注意:节点堆栈大小限制超过了大约400万,因此您无法运行这500万次,它永远无法完成。
function makeid()
{
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 5; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
ids ={}
count = 0
for (var i = 0; i < 1000000; i++) {
tempId = makeid();
if (typeof ids[tempId] !== 'undefined') {
ids[tempId]++;
if (ids[tempId] === 2) {
count ++;
}
count++;
}else{
ids[tempId] = 1;
}
}
console.log("there are "+count+ ' duplicate ids');