我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
当前回答
这个小巧的小把戏怎么样?
var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var stringLength = 5;
function pickRandom() {
return possible[Math.floor(Math.random() * possible.length)];
}
var randomString = Array.apply(null, Array(stringLength)).map(pickRandom).join('');
您需要Array.apply来将空数组变为未定义的数组。
如果您正在为ES2015进行编码,那么构建阵列会简单一些:
var randomString = Array.from({ length: stringLength }, pickRandom).join('');
其他回答
随机字符串生成器(字母数字|字母数字|数字)
/***伪随机串发生器* http://stackoverflow.com/a/27872144/383904*默认值:返回随机字母数字字符串* *@param{Integer}len所需长度*@param{String}an可选(字母数字),“a”(字母),“n”(数字)*@return{字符串}*/函数randomString(len,an){an=an&&an.toLowerCase();var str=“”,i=0,min=an==“a”?10 : 0,max=an==“n”?10 : 62;对于(;i++<len;){var r=数学随机()*(最大值-最小值)+最小值<<0;str+=String.fromCharCode(r+=r>9?r<36?55:61:48);}返回str;}console.log(randomString(10));//即:“4Z8INGag9v”console.log(randomString(10,“a”));//即:“aUkZuHNcWw”console.log(randomString(10,“n”));//即:“9055739230”
虽然以上使用了对期望的A/N、A、N输出的附加检查,让我们将其分解为基本要素(仅限字母数字),以便更好地理解:
创建一个接受参数的函数(随机字符串结果的所需长度)创建一个空字符串,如var str=“”;连接随机字符在循环内创建一个从0到61(0..9+a.Z+a..Z=62)的rand索引编号创建一个条件逻辑来调整/修复rand(因为它是0..61),将其递增一些数字(参见下面的示例),以获取正确的CharCode编号和相关字符。在循环内部连接到str一个String.fromCharCode(递增rand)
让我们想象一下ASCII字符表范围:
_____0....9______A..........Z______a..........z___________ Character
| 10 | | 26 | | 26 | Tot = 62 characters
48....57 65..........90 97..........122 CharCode ranges
Math.floor(Math.random*62)给出了从0..61(我们需要的)的范围。让我们修复随机数以获得正确的charCode范围:
| rand | charCode | (0..61)rand += fix = charCode ranges |
------+----------+----------+--------------------------------+-----------------+
0..9 | 0..9 | 48..57 | rand += 48 = 48..57 |
A..Z | 10..35 | 65..90 | rand += 55 /* 90-35 = 55 */ = 65..90 |
a..z | 36..61 | 97..122 | rand += 61 /* 122-61 = 61 */ = 97..122 |
上表中的条件运算逻辑:
rand += rand>9 ? ( rand<36 ? 55 : 61 ) : 48 ;
// rand += true ? ( true ? 55 else 61 ) else 48 ;
根据上面的解释,下面是生成的字母数字代码段:
函数randomString(len){var str=“”;//字符串结果对于(var i=0;i<len;i++){//循环“len”次数var rand=数学地板(Math.random()*62);//随机:0..61var charCode=rand+=rand>9?(兰特<36?55:61):48;//获取正确的charCodestr+=字符串.fromCharCode(charCode);//将字符添加到str}返回str;//完成所有循环后,返回连接字符串}console.log(randomString(10));//即:“7GL9F0ne6t”
或者,如果您愿意:
const randomString=(n,r=“”)=>{而(n--)r+=String.fromCharCode((r=Math.random()*62|0,r+=r>9?(r<36?55:61):48));返回r;};console.log(randomString(10))
"12345".split('').map(function(){return 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'.charAt(Math.floor(62*Math.random()));}).join('');
//or
String.prototype.rand = function() {return this.split('').map(function(){return 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'.charAt(Math.floor(62*Math.random()));}).join('');};
将生成长度为第一个/调用字符串的随机字母数字字符串
这是第一个答案的测试脚本(谢谢@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');
我想这会对你有用:
函数makeid(长度){let result=“”;const characters=‘EFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvxyz0123456789’;常量字符长度=字符长度;让计数器=0;while(计数器<长度){result+=characters.charAt(Math.floor(Math.random()*charactersLength));计数器+=1;}返回结果;}console.log(makeid(5));
你可以使用coderain。这是一个根据给定模式生成随机代码的库。使用#作为大写和小写字符以及数字的占位符:
var cr = new CodeRain("#####");
console.log(cr.next());
还有其他占位符,如A表示大写字母或9表示数字。
可能有用的是,调用.next()将始终为您提供唯一的结果,因此您不必担心重复。
这里是一个生成唯一随机代码列表的演示应用程序。
完全披露:我是《代码雨》的作者。