我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
当前回答
//返回随机字母
let alpha = "ABCDEFGHIGKLMNOPQRSTUVWXYZ";
console.log(alpha.charAt(Math.floor(Math.random() * alpha.length)));
其他回答
改进了上面@Andrew的回答:
Array.from({ length : 1 }, () => Math.random().toString(36)[2]).join('');
随机数的基数36转换是不一致的,因此选择一个标记可以解决这个问题。您可以使用所需的确切长度更改字符串的长度。
这是doubletap答案的稍微改进版本。当Math.random()返回0、0.5、0.25、0.125等时,它会考虑gertas对案例的评论。
((Math.random()+3*Number.MIN_VALUE)/Math.PI).toString(36).slice(-5)
它防止零被传递给toString,我将最小的浮点值添加到Math.random()。它确保传递给toString的数字有足够的数字,通过除以一个几乎不合理的数字。
生成包含aA zZ和0-9字符集合的随机字符串。只需使用长度参数调用此函数。
所以要回答这个问题:generateRandomString(5)
generateRandomString(length){
let result = "", seeds
for(let i = 0; i < length - 1; i++){
//Generate seeds array, that will be the bag from where randomly select generated char
seeds = [
Math.floor(Math.random() * 10) + 48,
Math.floor(Math.random() * 25) + 65,
Math.floor(Math.random() * 25) + 97
]
//Choise randomly from seeds, convert to char and append to result
result += String.fromCharCode(seeds[Math.floor(Math.random() * 3)])
}
return result
}
生成不带数字的字符串的版本:
generateRandomString(length){
let result = "", seeds
for(let i = 0; i < length - 1; i++){
seeds = [
Math.floor(Math.random() * 25) + 65,
Math.floor(Math.random() * 25) + 97
]
result += String.fromCharCode(seeds[Math.floor(Math.random() * 2)])
}
return result
}
[..."abcdefghijklmnopqrsuvwxyz0123456789"].map((e, i, a) => a[Math.floor(Math.random() * a.length)]).join('')
我想这会对你有用:
函数makeid(长度){let result=“”;const characters=‘EFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvxyz0123456789’;常量字符长度=字符长度;让计数器=0;while(计数器<长度){result+=characters.charAt(Math.floor(Math.random()*charactersLength));计数器+=1;}返回结果;}console.log(makeid(5));