我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
当前回答
下面这个怎么样。。。这将产生真正随机的值:
function getRandomStrings(length) {
const value = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const randoms = [];
for(let i=0; i < length; i++) {
randoms.push(value[Math.floor(Math.random()*value.length)]);
}
return randoms.join('');
}
但如果您在ES6中寻找一个较短的语法:
const getRandomStrings = length => Math.random().toString(36).substr(-length);
其他回答
这里有一些简单的一行。更改新阵列(5)以设置长度。
包括0-9a-z
new Array(5).join().replace(/(.|$)/g, function(){return ((Math.random()*36)|0).toString(36);})
包括0-9a-zA-Z
new Array(5).join().replace(/(.|$)/g, function(){return ((Math.random()*36)|0).toString(36)[Math.random()<.5?"toString":"toUpperCase"]();});
ES6编码(0-9a-z)
Array(5).fill().map(n=>(Math.random()*36|0).toString(36)).join('')
生成10个字符长的字符串。长度由参数设置(默认值为10)。
function random_string_generator(len) {
var len = len || 10;
var str = '';
var i = 0;
for(i=0; i<len; i++) {
switch(Math.floor(Math.random()*3+1)) {
case 1: // digit
str += (Math.floor(Math.random()*9)).toString();
break;
case 2: // small letter
str += String.fromCharCode(Math.floor(Math.random()*26) + 97); //'a'.charCodeAt(0));
break;
case 3: // big letter
str += String.fromCharCode(Math.floor(Math.random()*26) + 65); //'A'.charCodeAt(0));
break;
default:
break;
}
}
return str;
}
这是第一个答案的测试脚本(谢谢@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');
正如这里的几个人所指出的,将Math.random()的结果直接传递给.string(36)有几个问题。
它的随机性很差。生成的字符数量各不相同,平均而言取决于Javascript中浮点数如何工作的棘手细节。如果我试图生成11个或更少的字符,但不能生成超过11个字符,这似乎是有效的。而且它不灵活。允许或禁止某些字符是不容易的。
对于任何使用lodash的人,我有一个紧凑的解决方案,它没有这些问题:
_.range(11).map(i => _.sample("abcdefghijklmnopqrstuvwxyz0123456789")).join('')
如果要允许某些字符(例如大写字母)或禁止某些字符(如l和1等不明确的字符),请修改上面的字符串。
最紧凑的解决方案,因为切片比子字符串短。从字符串末尾减去允许避免由随机函数生成的浮点符号:
Math.random().toString(36).slice(-5);
甚至
(+new Date).toString(36).slice(-5);
更新:添加了一种使用btoa方法的方法:
btoa(Math.random()).slice(0, 5);
btoa(+new Date).slice(-7, -2);
btoa(+new Date).substr(-7, 5);
//使用Math.random和Base 36:console.log(Math.random().toString(36).slice(-5));//使用新的日期和基数36:console.log((+new Date).toString(36).slice(-5));//使用Math.random和Base 64(btoa):console.log(btoa(Math.random()).slice(0,5));//使用新的日期和基数64(btoa):console.log(btoa(+新日期).slice(-7,-2));console.log(btoa(+新日期).substr(-7,5));