我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
当前回答
这是第一个答案的测试脚本(谢谢@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');
其他回答
一个衬垫[a-z]:
String.fromCharCode(97 + Math.floor(Math.random() * 26))
//创建一个长度为10的随机代码,您可以随意更改它
function createRandomCode(length) {
let randomCodes = '';
let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let charactersLength = characters.length;
for (let i = 0; i < length; i++ ) {
randomCodes += characters.charAt(Math.floor(Math.random() * charactersLength))
}
console.log("your reference code is: ".toLocaleUpperCase() + randomCodes);
};
createRandomCode(10)
你可以使用coderain。这是一个根据给定模式生成随机代码的库。使用#作为大写和小写字符以及数字的占位符:
var cr = new CodeRain("#####");
console.log(cr.next());
还有其他占位符,如A表示大写字母或9表示数字。
可能有用的是,调用.next()将始终为您提供唯一的结果,因此您不必担心重复。
这里是一个生成唯一随机代码列表的演示应用程序。
完全披露:我是《代码雨》的作者。
生成安全的随机字母数字Base-62字符串:
函数生成UID(长度){return window.btoa(String.fromCharCode(…window.crypto.getRandomValues(新Uint8Array(长度*2))).replace(/[+/]/g,“”).substring(0,长度);}console.log(生成UID(22));//“yFg3Upv2cE9cKOXd7hHwWp”console.log(生成UID(5));//“YQGzP”
生成任意数量的十六进制字符(例如32):
(function(max){let r='';for(let i=0;i<max/13;i++)r+=(Math.random()+1).toString(16).substring(2);return r.substring(0,max).toUpperCase()})(32);