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

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


当前回答

//可以将7更改为2以获得更长的结果。让r=(Math.random()+1).toString(36).substring(7);console.log(“随机”,r);

注:上述算法有以下缺点:

它将生成0到6个字符之间的任何字符,这是因为字符串化浮点时会删除尾随零。这在很大程度上取决于用于字符串化浮点数的算法,这非常复杂。(请参阅论文“如何准确打印浮点数字”。)根据实现的不同,Math.random()可能会产生可预测的(“看起来随机”但不是真正随机的)输出。当需要保证唯一性或不可预测性时,生成的字符串不适合。即使它产生了6个统一的随机、不可预测的字符,由于生日悖论,在只产生了大约50000个字符串之后,你也可以看到重复的字符。(平方英尺(36^6)=4656)

其他回答

function generate(length) {
  var letters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","0","1","2","3","4","5","6","7","8","9"];
  var IDtext = "";
  var i = 0;
  while (i < length) {
    var letterIndex = Math.floor(Math.random() * letters.length);
    var letter = letters[letterIndex];
    IDtext = IDtext + letter;
    i++;
  }
  console.log(IDtext)
}

我想这会对你有用:

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

一行使用地图,可以完全控制长度和字符。

const rnd = (len, chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') => [...Array(len)].map(() => chars.charAt(Math.floor(Math.random() * chars.length))).join('')

console.log(rnd(12))

我没有找到支持小写和大写字符的干净解决方案。

仅小写支持:

Math.random().toString(36).substr(2,5)

基于该解决方案,支持小写和大写:

Math.random().toString(36).substr(2,5).split(“”).map(c=>Math.randm()<0.5?c.toUpperCase():c).jjoin(“”);

更改substr(2,5)中的5以调整到所需的长度。

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

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);

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