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

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


当前回答

例如,如果你想要一个随机的DNA序列,你可以循环遍历一个项目数组并递归地将它们添加到字符串变量中:

功能随机DNA(len){len=长度||100var nuc=新阵列(“A”、“T”、“C”、“G”)变量i=0变量n=0s=“”而(i<=len-1){n=数学楼层(Math.random()*4)s+=努克[n]我++}返回s}console.log(随机DNA(5));

其他回答

这里有一些简单的一行。更改新阵列(5)以设置长度。

包括0-9a-z

new Array(5).join().replace(/(.|$)/g, function(){return ((Math.random()*36)|0).toString(36);})

包括0-9a-zA-Z

new Array(5).join().replace(/(.|$)/g, function(){return ((Math.random()*36)|0).toString(36)[Math.random()<.5?"toString":"toUpperCase"]();});

ES6编码(0-9a-z)

Array(5).fill().map(n=>(Math.random()*36|0).toString(36)).join('')
function randomString (strLength, charSet) {
    var result = [];
    
    strLength = strLength || 5;
    charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    
    while (strLength--) { // (note, fixed typo)
        result.push(charSet.charAt(Math.floor(Math.random() * charSet.length)));
    }
    
    return result.join('');
}

这是最干净的了。它也很快,http://jsperf.com/ay-random-string.

最紧凑的解决方案,因为切片比子字符串短。从字符串末尾减去允许避免由随机函数生成的浮点符号:

Math.random().toString(36).slice(-5);

甚至

(+new Date).toString(36).slice(-5);

更新:添加了一种使用btoa方法的方法:

btoa(Math.random()).slice(0, 5);
btoa(+new Date).slice(-7, -2);
btoa(+new Date).substr(-7, 5);

//使用Math.random和Base 36:console.log(Math.random().toString(36).slice(-5));//使用新的日期和基数36:console.log((+new Date).toString(36).slice(-5));//使用Math.random和Base 64(btoa):console.log(btoa(Math.random()).slice(0,5));//使用新的日期和基数64(btoa):console.log(btoa(+新日期).slice(-7,-2));console.log(btoa(+新日期).substr(-7,5));

npm模块anyid提供了灵活的API来生成各种字符串ID/代码。

const id = anyid().encode('Aa0').length(5).random().id();

随机数值(最多16位)

/**
 * Random numeric value (up to 16 digits)
 * @returns {String}
 */
function randomUid () {
  return String(Math.floor(Math.random() * 9e15))
}

// randomUid() -> "3676724552601324"