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


当前回答

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

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.

其他回答

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

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.

32个字符:

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

这样更干净

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

例子

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

当我看到这个问题时,我想到了我必须生成uuid的时候。我不能把代码的功劳,因为我确信我在stackoverflow上找到了它。如果你不想在字符串中使用破折号,那就去掉破折号。函数如下:

function generateUUID() {
    var d = new Date().getTime();
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,function(c) {
        var r = (d + Math.random()*16)%16 | 0;
        d = Math.floor(d/16);
        return (c=='x' ? r : (r&0x7|0x8)).toString(16);
    });
    return uuid.toUpperCase();
}

小提琴:http://jsfiddle.net/nlviands/fNPvf/11227/

这个函数应该给出任意长度的随机字符串。

function randString(length) {
    var l = length > 25 ? 25 : length;
    var str = Math.random().toString(36).substr(2, l);
    if(str.length >= length){
        return str;
    }
    return str.concat(this.randString(length - str.length));
}

我用下面的测试成功地测试了它。

function test(){
    for(var x = 0; x < 300000; x++){
        if(randString(x).length != x){
            throw new Error('invalid result for len ' + x);
        }
    }
}

我选择25的原因是,在实践中,从Math.random(). tostring(36)返回的字符串长度。Substr(2,25)的长度为25。这个数字可以根据您的意愿更改。

此函数是递归的,因此使用非常大的值调用函数可能会导致超过最大调用堆栈大小。从我的测试中,我能够得到长度为30万字符的字符串。

通过将字符串作为第二个参数发送给函数,可以将该函数转换为尾递归。我不确定JS是否使用Tail调用优化