我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
当前回答
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.
其他回答
我知道每个人都已经做好了,但我想以最轻量级的方式(轻代码,而不是CPU)尝试一下:
函数rand(长度,电流){电流=电流?当前:“”;返回长度?rand(--length,“0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvxyz”.charAt(Math.floor(Math.random()*60))+电流):电流;}console.log(rand(5));
这需要一点时间来理解,但我认为它确实显示了javascript的语法是多么棒。
将字符作为thisArg放在map函数中会创建一个“单行”:
Array.apply(null, Array(5))
.map(function(){
return this[Math.floor(Math.random()*this.length)];
}, "abcdefghijklmnopqrstuvwxyz")
.join('');
通过回答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/
短、简单、可靠
返回5个随机字符,而不是此处找到的一些排名最高的答案。
Math.random().toString(36).slice(2, 7);
非常简单
function getRandomColor(){
var color='';
while(color.length<6){
color=Math.floor(Math.random()*16777215).toString(16);
}
return '#'+color;
}