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


当前回答

这是一个简单的代码来生成随机字符串字母。 看看这段代码是如何工作的。 去(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;
}

其他回答

随机密钥生成器

keyLength参数是你想要的键的字符长度

function keyGen(keyLength) {
    var i, key = "", characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    var charactersLength = characters.length;

    for (i = 0; i < keyLength; i++) {
        key += characters.substr(Math.floor((Math.random() * charactersLength) + 1), 1);
    }

    return key;
}


keyGen(12)
"QEt9mYBiTpYD"

beans建议的另一种答案变体

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

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

我使用@Nimphious优秀的第二种方法,发现偶尔返回的字符串是数字-而不是字母数字。 我使用的解决方案是测试使用!isNaN,并再次使用递归调用该函数。 何苦呢?我使用这个函数来创建对象键,如果所有的键都是字母数字,那么所有的键都可以正常排序,但如果你使用 数字作为键与字母数字(字符串)混合在一起循环遍历对象将产生与原始顺序不同的顺序。

function newRandomString(length, chars) {
  var mask = '';
  if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
  if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  if (chars.indexOf('#') > -1) mask += '0123456789';
  if (chars.indexOf('$') > -1) mask += '0123456789';

  var result = '';
  for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() * 
  mask.length)];
  /*    
        we need a string not a number !isNaN(result)) will return true if '1234' or '3E77'
        because if we're looping through object keys (created by newRandomString()) and 
        a number is used and all the other keys are strings then the number will 
        be first even if it was the 2nd or third key in object
  */
  //use recursion to try again
  if(!isNaN(result)){
    console.log('found a number....:'+result);
    return newRandomString(length, chars)
  }else{
    return result;
  }
};

var i=0;
while (i < 1000) {
  var a = newRandomString(4, '#$aA');
  console.log(i+' - '+a);
  //now we're using recursion this won't occur
  if(!isNaN(a)){
    console.log('=============='+i+' - '+a);
  }
  i++;
}

console.log('3E77:'+!isNaN('3E77'));//true
console.log('1234:'+!isNaN('1234'));//true
console.log('ab34:'+!isNaN('ab34'));//false

使用md5库:https://github.com/blueimp/JavaScript-MD5

最短的方法:

md5(随机数学。()

如果你想限制大小为5:

md5 (math . random())。substr (0, 5)

更新: 一行程序解决方案,随机20个字符(字母数字小写):

Array.from(Array(20), () => Math.floor(Math.random() * 36).toString(36)).join('');

或者用lodash更短:

_.times(20, () => _.random(35).toString(36)).join('');