我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
当前回答
这是我用过的。这是一对夫妇的组合。我在循环中使用它,它生成的每个ID都是唯一的。它可能不是5个字符,但它保证是唯一的。
var newId =
"randomid_" +
(Math.random() / +new Date()).toString(36).replace(/[^a-z]+/g, '');
其他回答
像这样扩展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));
函数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));
假设您使用underscorejs,就可以在两行中优雅地生成随机字符串:
var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var random = _.sample(possible, 5).join('');
我喜欢doubletap的Math.random().toString(36).substring(7)答案的简洁,但并不是因为它有很多像hack-likecrack正确指出的冲突。它生成了11个字符字符串,但在100万个样本中,重复率为11%。
这里有一个更长(但仍然很短)、更慢的替代方案,在100万个样本空间中只有133个副本。在极少数情况下,字符串仍将短于11个字符:
Math.abs(Math.random().toString().split('')
.reduce(function(p,c){return (p<<5)-p+c})).toString(36).substr(0,11);
功能性方法。只有在应用程序的其他部分可以利用功能先决条件时,这个答案才实用。表演可能是垃圾,但写起来非常有趣。
//功能先决条件常量U=f=>f(f)常量Y=U(h=>f=>f(x=>h(h)(f)(x)))常量comp=f=>g=>x=>f(g(x))常量foldk=Y(h=>f=>Y=>([x,…xs])=>x===未定义?y:f(y)(x)(y=>h(f)(y))(xs))常量fold=f=>foldk(y=>x=>k=>k(f(y)(x)))常量映射=f=>fold(y=>x=>[…y,f(x)])([])constchar=x=>String.fromCharCode(x)常量concat=x=>y=>y.concat(x)常量concatMap=f=>comp(fold(concat)([]))(map(f))const irand=x=>数学地板(Math.random()*x)常量样本=xs=>xs[irand(xs.length)]//范围:从x到y的范围;[x…y]//编号->编号->[编号]常量范围=Y(f=>r=>x=>Y=>x>y?r:f([…r,x])(x+1)(y)) ([])//srand:从列表或ascii代码范围生成随机字符串//[(范围a)]->编号->[a]常量srand=comp(Y(f=>z=>rs=>x=>x===0?z:f(z+样本(rs))(rs)(x-1))([]))(concatMap(map(char)))//idGenerator:生成指定长度的标识符//数字->字符串常量idGenerator=srand([范围(48)(57),//包括0-9范围(65)(90),//包括A-Z范围(97)(122)//包括a-z])console.log(idGenerator(6))//=>TT688Xconsole.log(idGenerator(10))//=>SzaaUBlpI1console.log(idGenerator(20))//=>eYAaWhsfvLDhIBID1xRh
在我看来,如果不添加神奇的、做太多事情的功能,很难超越idGenerator的清晰度。
稍有改进
// ord : convert char to ascii code
// Char -> Number
const ord = x => x.charCodeAt(0)
// idGenerator : make an identifier of specified length
// Number -> String
const idGenerator = srand ([
range (ord('0')) (ord('9')),
range (ord('A')) (ord('Z')),
range (ord('a')) (ord('z'))
])
玩得开心。让我知道你喜欢/学习什么^_^