我希望得到一个由随机选取的字符组成的5个字符的字符串,可用字符集为
使用JavaScript,最佳方法是什么?
[a-zA-Z0-9]
。使用JavaScript,最佳方法是什么?
[a-zA-Z0-9]
。var randNo = Math.floor(Math.random() * 100) + 2 + "" + new Date().getTime() + Math.floor(Math.random() * 100) + 2 + (Math.random().toString(36).replace(/[^a-zA-Z]+/g, '').substr(0, 5));
console.log(randNo);
Date.now().toString(36)
?它不算是非常随机,但每次调用都会生成一个短小且相当独特的值。Date.now()
只有毫秒分辨率。例如在简单的循环中运行时,你会得到很多重复的值。 for (let i = 0; i < 10; ++i) { console.log(Date.now().toString(36)); }
。 - Nate如果你在开发Node.js应用程序,建议使用crypto模块。以下是实现randomStr()
函数的示例。
const crypto = require('crypto');
const charset = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz';
const randomStr = (length = 5) => new Array(length)
.fill(null)
.map(() => charset.charAt(crypto.randomInt(charset.length)))
.join('');
如果你不是在服务器环境中工作,只需替换随机数生成器:
const charset = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz';
const randomStr = (length = 5) => new Array(length)
.fill(null)
.map(() => charset.charAt(Math.floor(Math.random() * charset.length)))
.join('');
这是我使用的代码。结合了几个方法。我在一个循环中使用它,每个生成的ID都是唯一的。它可能不是5个字符,但是保证唯一性。
var newId =
"randomid_" +
(Math.random() / +new Date()).toString(36).replace(/[^a-z]+/g, '');
makeid()
,你可以看到5并不是非常独特的数字。使用10个字符长度运行它是相当可靠的。我已经运行了大约50次,并没有看到重复的情况:-)
。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');
#
作为大写和小写字符以及数字的占位符:var cr = new CodeRain("#####");
console.log(cr.next());
除了占位符X
之外,其他常用的占位符还有大写字母A
和数字9
。
值得注意的是,调用.next()
方法总会给你一个唯一的结果,因此您不必担心重复。
这里有一个演示应用程序,它生成一系列独特的随机代码。
完全透明:我是coderain的作者。
在Doubletap的优雅示例基础上,回答Gertas和Dragon提出的问题。只需添加一个while循环以测试这些罕见的null情况,并将字符限制为五个。
function rndStr() {
x=Math.random().toString(36).substring(7).substr(0,5);
while (x.length!=5){
x=Math.random().toString(36).substring(7).substr(0,5);
}
return x;
}
对于包含大写字母、小写字母和数字(0-9a-zA-Z)的字符串,以下版本可能是最优的代码压缩版本:
function makeId(length) {
var id = '';
var rdm62;
while (length--) {
// Generate random integer between 0 and 61, 0|x works for Math.floor(x) in this case
rdm62 = 0 | Math.random() * 62;
// Map to ascii codes: 0-9 to 48-57 (0-9), 10-35 to 65-90 (A-Z), 36-61 to 97-122 (a-z)
id += String.fromCharCode(rdm62 + (rdm62 < 10 ? 48 : rdm62 < 36 ? 55 : 61))
}
return id;
}
为了保存纪念,请发布一个符合ES6标准的版本。如果这个代码被频繁调用,请确保将.length值存储在常量变量中。
// USAGE:
// RandomString(5);
// RandomString(5, 'all');
// RandomString(5, 'characters', '0123456789');
const RandomString = (length, style = 'frictionless', characters = '') => {
const Styles = {
'all': allCharacters,
'frictionless': frictionless,
'characters': provided
}
let result = '';
const allCharacters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const frictionless = 'ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789';
const provided = characters;
const generate = (set) => {
return set.charAt(Math.floor(Math.random() * set.length));
};
for ( let i = 0; i < length; i++ ) {
switch(Styles[style]) {
case Styles.all:
result += generate(allCharacters);
break;
case Styles.frictionless:
result += generate(frictionless);
break;
case Styles.characters:
result += generate(provided);
break;
}
}
return result;
}
export default RandomString;