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


当前回答

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

最短的方法:

md5(随机数学。()

如果你想限制大小为5:

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

其他回答

我只是发现了一个非常好的优雅的解决方案:

Math.random().toString(36).slice(2)

这个实现的注意事项:

This will produce a string anywhere between zero and 12 characters long, usually 11 characters, due to the fact that floating point stringification removes trailing zeros. It won't generate capital letters, only lower-case and numbers. Because the randomness comes from Math.random(), the output may be predictable and therefore not necessarily unique. Even assuming an ideal implementation, the output has at most 52 bits of entropy, which means you can expect a duplicate after around 70M strings generated.

使用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 " > < / >

随机字符:

String.fromCharCode(i); //where is an int

随机整数:

Math.floor(Math.random()*100);

把它们放在一起:

function randomNum(hi){
    return Math.floor(Math.random()*hi);
} 
function randomChar(){
    return String.fromCharCode(randomNum(100));
}
function randomString(length){
   var str = "";
   for(var i = 0; i < length; ++i){
        str += randomChar();
   }
   return str;
}
var RandomString = randomString(32); //32 length string

小提琴:http://jsfiddle.net/maniator/QZ9J2/

在看了这个问题的答案和其他来源的答案后,这是最简单的解决方案,同时允许修改所包含的字符和选择返回结果的长度。

// generate random string of n characters
function randomString(length) {
    const characters = '0123456789abcdefghijklmnopqrstuvwxyz'; // characters used in string
    let result = ''; // initialize the result variable passed out of the function
    for (let i = length; i > 0; i--) {
        result += characters[Math.floor(Math.random() * characters.length)];
    }
    return result;
}

console.log(randomString(6));

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

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

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