在JavaScript中生成一个随机的字母数字(大写,小写和数字)字符串来用作可能唯一的标识符的最短方法是什么?


当前回答

var randomString = function(length) {
  var str = '';
  var chars ='0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split(
      '');
  var charsLen = chars.length;
  if (!length) {
    length = ~~(Math.random() * charsLen);
  }
  for (var i = 0; i < length; i++) {
    str += chars[~~(Math.random() * charsLen)];
  }
  return str;
};

其他回答

这是一个简单的代码来生成随机字符串字母。 看看这段代码是如何工作的。 去(lenthOfStringToPrint);-使用此函数生成最终字符串。

var letters = {
  1: ["q","w","e","r","t","y","u","i","o","p","a","s","d","f","g","h","j","k","l","z","x","c","v","b","n","m"],
  2: ["Q","W","E","R","T","Y","U","I","O","P","A","S","D","F","G","H","J","K","L","Z","X","C","V","B","N","M"]
},i,letter,final="";
random = (max,min) => {
  return Math.floor(Math.random()*(max-min+1)+min);
}
function go(length) {
  final="",letter="";
  for (i=1; i<=length; i++){
    letter = letters[random(0,3)][random(0,25)];
    final+=letter;
  }
  return final;
}

beans建议的另一种答案变体

(Math.random()*1e32).toString(36)

通过改变乘数1e32,你可以改变随机字符串的长度。

32个字符:

for(var c = ''; c.length < 32;) c += Math.random().toString(36).substr(2, 1)

一个取长度的简单函数

getRandomToken(len: number): string {
  return Math.random().toString(36).substr(2, len);
}

如果你传递6,它会生成6位字母数字

可以使用lodash uniqueId:

    _.uniqueId([prefix=''])

生成唯一的ID。如果给出了prefix,则ID被追加到它后面。