我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。

用JavaScript实现这一点的最佳方法是什么?


当前回答

正如这里的几个人所指出的,将Math.random()的结果直接传递给.string(36)有几个问题。

它的随机性很差。生成的字符数量各不相同,平均而言取决于Javascript中浮点数如何工作的棘手细节。如果我试图生成11个或更少的字符,但不能生成超过11个字符,这似乎是有效的。而且它不灵活。允许或禁止某些字符是不容易的。

对于任何使用lodash的人,我有一个紧凑的解决方案,它没有这些问题:

_.range(11).map(i => _.sample("abcdefghijklmnopqrstuvwxyz0123456789")).join('')

如果要允许某些字符(例如大写字母)或禁止某些字符(如l和1等不明确的字符),请修改上面的字符串。

其他回答

如果您是在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('');

我想这会对你有用:

函数makeid(长度){let result=“”;const characters=‘EFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvxyz0123456789’;常量字符长度=字符长度;让计数器=0;while(计数器<长度){result+=characters.charAt(Math.floor(Math.random()*charactersLength));计数器+=1;}返回结果;}console.log(makeid(5));

将字符作为thisArg放在map函数中会创建一个“单行”:

Array.apply(null, Array(5))
.map(function(){ 
    return this[Math.floor(Math.random()*this.length)];
}, "abcdefghijklmnopqrstuvwxyz")
.join('');

这是Coffeescapet版本的一行代码

genRandomString = (length,set) -> [0...length].map( -> set.charAt Math.floor(Math.random() * set.length)).join('')

用法:

genRandomString 5, 'ABCDEFTGHIJKLMNOPQRSTUVWXYZ'

输出:

'FHOOV' # random string of length 5 in possible set A~Z

我使用var randId='rand'+new Date().getTime();