我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
当前回答
像这样扩展String对象怎么样。
String.prototype.random = function(length) {
var result = '';
for (var i = 0; i < length; i++) {
result += this.charAt(Math.floor(Math.random() * this.length));
}
return result;
};
使用它:
console.log("ABCDEFG".random(5));
其他回答
这是doubletap答案的稍微改进版本。当Math.random()返回0、0.5、0.25、0.125等时,它会考虑gertas对案例的评论。
((Math.random()+3*Number.MIN_VALUE)/Math.PI).toString(36).slice(-5)
它防止零被传递给toString,我将最小的浮点值添加到Math.random()。它确保传递给toString的数字有足够的数字,通过除以一个几乎不合理的数字。
这是我创建的方法。它将创建一个包含大小写字符的字符串。此外,我还包含了将创建字母数字字符串的函数。
工作示例:http://jsfiddle.net/greatbigmassive/vhsxs/(仅限alpha)http://jsfiddle.net/greatbigmassive/PJwg8/(字母数字)
function randString(x){
var s = "";
while(s.length<x&&x>0){
var r = Math.random();
s+= String.fromCharCode(Math.floor(r*26) + (r>0.5?97:65));
}
return s;
}
2015年7月升级这做了同样的事情,但更有意义,包括所有字母。
var s = "";
while(s.length<x&&x>0){
v = Math.random()<0.5?32:0;
s += String.fromCharCode(Math.round(Math.random()*((122-v)-(97-v))+(97-v)));
}
最紧凑的解决方案,因为切片比子字符串短。从字符串末尾减去允许避免由随机函数生成的浮点符号:
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));
函数randomstring(L){var s=“”;var randomchar=函数(){var n=数学地板(Math.random()*62);如果(n<10)返回n//1-10如果(n<36)返回String.fromCharCode(n+55)//A-Z型return String.fromCharCode(n+61)//a-z型}而(s.length<L)s+=randomchar();返回s;}console.log(随机字符串(5));
非常简单
function getRandomColor(){
var color='';
while(color.length<6){
color=Math.floor(Math.random()*16777215).toString(16);
}
return '#'+color;
}