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

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


当前回答

如果只需要大写字母(A-Z):

randomAZ(n: number): string {
      return Array(n)
        .fill(null)
        .map(() => Math.random()*100%25 + 'A'.charCodeAt(0))
        .map(a => String.fromCharCode(a))
        .join('')
 }

如果您只希望第一个字母大写(A-Z),其余字母小写(A-Z):

function RandomWord(n: number): string {
    return Array(n)
      .fill(null)
      .map(() => Math.random()*100%25 + 'A'.charCodeAt(0))
      .map((a, i) => i === 0? String.fromCharCode(a) : String.fromCharCode(a+32))
      .join('')
}

其他回答

这一个结合了许多给出的答案。

var randNo=Math.floor(Math.random()*100)+2+“”+new Date().getTime()+Math.floof(Math.rrandom()*100)+2+(Math.rand().toString(36).replace(/[^a-zA-Z]+/g,'').substr(0,5));console.log(randNo);

我用了一个月,效果很好。

这里有一些简单的一行。更改新阵列(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('')

最简单的方法是:

(new Date%9e6).toString(36)

这将基于当前时间生成5个字符的随机字符串。示例输出为4mtxj或4mv90或4mwp1

这样做的问题是,如果您在同一秒内调用它两次,它将生成相同的字符串。

更安全的方法是:

(0|Math.random()*9e6).toString(36)

这将生成一个4或5个字符的随机字符串,总是不同的。示例输出类似于30jzm或1r591或4su1a

在这两种方式中,第一部分生成一个随机数。.toString(36)部分将数字转换为它的base36(字母十进制)表示形式。

我喜欢doubletap的Math.random().toString(36).substring(7)答案的简洁,但并不是因为它有很多像hack-likecrack正确指出的冲突。它生成了11个字符字符串,但在100万个样本中,重复率为11%。

这里有一个更长(但仍然很短)、更慢的替代方案,在100万个样本空间中只有133个副本。在极少数情况下,字符串仍将短于11个字符:

Math.abs(Math.random().toString().split('')
    .reduce(function(p,c){return (p<<5)-p+c})).toString(36).substr(0,11);

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