我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
当前回答
将字符作为thisArg放在map函数中会创建一个“单行”:
Array.apply(null, Array(5))
.map(function(){
return this[Math.floor(Math.random()*this.length)];
}, "abcdefghijklmnopqrstuvwxyz")
.join('');
其他回答
功能性方法。只有在应用程序的其他部分可以利用功能先决条件时,这个答案才实用。表演可能是垃圾,但写起来非常有趣。
//功能先决条件常量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'))
])
玩得开心。让我知道你喜欢/学习什么^_^
对于包含大小写字母和数字(0-9a-zA-Z)的字符串,这可能是缩小效果最好的版本:
function makeId(length) {
var id = '';
var rdm62;
while (length--) {
// Generate random integer between 0 and 61, 0|x works for Math.floor(x) in this case
rdm62 = 0 | Math.random() * 62;
// Map to ascii codes: 0-9 to 48-57 (0-9), 10-35 to 65-90 (A-Z), 36-61 to 97-122 (a-z)
id += String.fromCharCode(rdm62 + (rdm62 < 10 ? 48 : rdm62 < 36 ? 55 : 61))
}
return id;
}
此函数的内容缩小到97个字节,而顶部答案需要149个字节(因为字符列表)。
喜欢这个SO问题和他们的答案。因此,提出了更具创意的解决方案。我提出了一个封装在函数中的函数,该函数接收要获取的字符串的长度加上一个模式参数,以决定如何编写字符串。
模式是一个3长度的字符串,只接受“1s”和“0s”,它们定义了要在最终字符串中包含的字符子集。它由3个不同的子集([0-9]、[A-B]、[A-B])分组
'100': [0-9]
'010': [A-B]
'101': [0-9] + [a-b]
'111': [0-9] + [A-B] + [a-b]
有8种可能的组合(2^N,其中N:#子集)。“000”模式返回空字符串。
function randomStr(l = 1, mode = '111') {
if (mode === '000') return '';
const r = (n) => Math.floor(Math.random() * n);
const m = [...mode].map((v, i) => parseInt(v, 10) * (i + 1)).filter(Boolean).map((v) => v - 1);
return [...new Array(l)].reduce((a) => a + String.fromCharCode([(48 + r(10)), (65 + r(26)), (97 + r(26))][m[r(m.length)]]), '')
}
一个简单的用例是:
random = randomStr(50, '101')
// ii3deu9i4jk6dp4gx43g3059vss9uf7w239jl4itv0cth5tj3e
// Will give you a String[50] composed of [0-9] && [a-b] chars only.
这里的主要思想是使用UNICODE表,而不是像我在许多答案中看到的那样随机化十六进制。这种方法的强大之处在于,您可以很容易地将其扩展为包含UNICODE表的其他子集,其中包含一些随机int(16)无法完成的额外代码。
如果您是在node js上开发,最好使用crypto。下面是实现randomStr()函数的示例
const crypto = require('crypto');
const charset = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz';
const randomStr = (length = 5) => new Array(length)
.fill(null)
.map(() => charset.charAt(crypto.randomInt(charset.length)))
.join('');
如果您不是在服务器环境中工作,只需更换随机数生成器:
const charset = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz';
const randomStr = (length = 5) => new Array(length)
.fill(null)
.map(() => charset.charAt(Math.floor(Math.random() * charset.length)))
.join('');
一行使用地图,可以完全控制长度和字符。
const rnd = (len, chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') => [...Array(len)].map(() => chars.charAt(Math.floor(Math.random() * chars.length))).join('')
console.log(rnd(12))