我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。

用JavaScript实现这一点的最佳方法是什么?


当前回答

以下是CoffeeScript中的示例:

String::add_Random_Letters   = (size )->
                                         charSet = 'abcdefghijklmnopqrstuvwxyz'
                                         @ + (charSet[Math.floor(Math.random() * charSet.length)]  for i in [1..size]).join('')

可以使用

value = "abc_"
value_with_exta_5_random_letters = value.add_Random_Letters(5)

其他回答

这是第一个答案的测试脚本(谢谢@csharptest.net)

该脚本运行makeid()100万次,如您所见,5不是一个非常独特的脚本。以10的字符长度运行它是非常可靠的。我已经运行了大约50次,还没有看到重复的:-)

注意:节点堆栈大小限制超过了大约400万,因此您无法运行这500万次,它永远无法完成。

function makeid()
{
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for( var i=0; i < 5; i++ )
        text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
}

ids ={}
count = 0
for (var i = 0; i < 1000000; i++) {
    tempId = makeid();
    if (typeof ids[tempId] !== 'undefined') {
        ids[tempId]++;
        if (ids[tempId] === 2) {
            count ++;
        }
        count++;
    }else{
        ids[tempId] = 1;
    }
}
console.log("there are "+count+ ' duplicate ids');
",,,,,".replace(/,/g,function (){return "AzByC0xDwEv9FuGt8HsIrJ7qKpLo6MnNmO5lPkQj4RiShT3gUfVe2WdXcY1bZa".charAt(Math.floor(Math.random()*62))});

通过回答Gertas和Dragon提出的问题,扩展Doubletap的优雅示例。只需添加一个while循环来测试那些罕见的空情况,并将字符限制为五个。

function rndStr() {
    x=Math.random().toString(36).substring(7).substr(0,5);
    while (x.length!=5){
        x=Math.random().toString(36).substring(7).substr(0,5);
    }
    return x;
}

这里有一个jsfiddle提示您一个结果:http://jsfiddle.net/pLJJ7/

将字符作为thisArg放在map函数中会创建一个“单行”:

Array.apply(null, Array(5))
.map(function(){ 
    return this[Math.floor(Math.random()*this.length)];
}, "abcdefghijklmnopqrstuvwxyz")
.join('');

不区分大小写的字母数字字符:

函数randStr(len){让s=“”;而(s.length<len)s+=Math.random().toString(36).substr(2,len-s.length);返回s;}//用法console.log(randStr(50));

此函数的好处是可以获得不同长度的随机字符串,并确保字符串的长度。

区分大小写的所有字符:

函数randStr(len){让s=“”;而(len--)s+=String.fromCodePoint(Math.floor(Math.random()*(126-33)+33));返回s;}//用法console.log(randStr(50));

自定义字符

函数randStr(len,chars='abc123'){让s=“”;而(len--)s+=字符[Math.floor(Math.random()*chars.length)];返回s;}//用法console.log(randStr(50));console.log(randStr(50,'abc'));console.log(randStr(50,'aab'));//a多于b