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


当前回答

可以使用lodash uniqueId:

    _.uniqueId([prefix=''])

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

其他回答

使用lodash:

生物多样性功能(length) var chars =“不可能” 瓦尔pwd = _sampleSize (chars,长度正好| | 12)/ lodash v4:用_ sampleSize。 pwd归来加入(“”)。 的 文件写(createRandomString(8)。 <剧本剧本src = " https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js " > < / >

beans建议的另一种答案变体

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

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

我认为以下是允许给定长度的最简单的解决方案:

Array(myLength).fill(0).map(x => Math.random().toString(36).charAt(2)).join('')

这取决于箭头函数的语法。

随机密钥生成器

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"

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