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

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


当前回答

加密强

如果您想获得满足您要求的加密强字符串(我看到的答案使用了这个,但给出了无效答案),请使用

let pass = n=> [...crypto.getRandomValues(new Uint8Array(n))]
   .map((x,i)=>(i=x/255*61|0,String.fromCharCode(i+(i>9?i>35?61:55:48)))).join``

let pass=n=>[…crypto.getRandomValues(新Uint8Array(n))].map((x,i)=>(i=x/255*61|0,String.fromCharCode(i+(i>9?i>35?61:55:48))).join``console.log(通过(5));

更新:感谢Zibri评论,我更新代码以获得任意长密码

其他回答

最简单的方法是:

(new Date%9e6).toString(36)

这将基于当前时间生成5个字符的随机字符串。示例输出为4mtxj或4mv90或4mwp1

这样做的问题是,如果您在同一秒内调用它两次,它将生成相同的字符串。

更安全的方法是:

(0|Math.random()*9e6).toString(36)

这将生成一个4或5个字符的随机字符串,总是不同的。示例输出类似于30jzm或1r591或4su1a

在这两种方式中,第一部分生成一个随机数。.toString(36)部分将数字转换为它的base36(字母十进制)表示形式。

同样基于doubletap的答案,该方法处理任意长度的随机所需字符(仅限小写),并不断生成随机数,直到收集到足够的字符。

function randomChars(len) {
    var chars = '';

    while (chars.length < len) {
        chars += Math.random().toString(36).substring(2);
    }

    // Remove unnecessary additional characters.
    return chars.substring(0, len);
}

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

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

递归解决方案:

function generateRamdomId (seedStr) {
const len = seedStr.length
console.log('possibleStr', seedStr , ' len ', len)
if(len <= 1){
    return seedStr
}
const randomValidIndex  = Math.floor(Math.random() * len)
const randomChar = seedStr[randomValidIndex]
const chunk1 = seedStr.slice(0, randomValidIndex)
const chunk2 = seedStr.slice(randomValidIndex +1)
const possibleStrWithoutRandomChar = chunk1.concat(chunk2)

return randomChar + generateRamdomId(possibleStrWithoutRandomChar)

}

你可以用你想要的种子,如果你不想,不要重复字符。实例

generateRandomId("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") 

通过回答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/