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

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


当前回答

我没有找到支持小写和大写字符的干净解决方案。

仅小写支持:

Math.random().toString(36).substr(2,5)

基于该解决方案,支持小写和大写:

Math.random().toString(36).substr(2,5).split(“”).map(c=>Math.randm()<0.5?c.toUpperCase():c).jjoin(“”);

更改substr(2,5)中的5以调整到所需的长度。

其他回答

如果可以使用库,Chance.js可能会有所帮助:http://chancejs.com/#string

最重要的是,所有的答案都是完美的。但我要补充的是,生成任何随机字符串值都非常好而且快速

函数randomStringGenerator(stringLength){var randomString=“”;//选择变量的空值const allCharacters=“`~!@#$%^&*()_+-={}[]:;\'<>?,./|\\ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijlmnopqrstuvwxyz0123456789'”;//所有字母数字字母列表while(stringLength--){randomString+=allCharacters.substr(Math.floor((Math.random()*allCharacters.length)+1),1);//使用Math.random()从所有字符变量中选择任意值}return randomString;//返回生成的字母数字字符串}console.log(randomStringGenerator(10))//通过输入所需的随机字符串来调用函数

or

console.log(Date.now())//它每次都会产生随机的十三个数字字符值。console.log(Date.now().toString().length)//打印生成字符串的长度

"12345".split('').map(function(){return 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'.charAt(Math.floor(62*Math.random()));}).join('');

//or

String.prototype.rand = function() {return this.split('').map(function(){return 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'.charAt(Math.floor(62*Math.random()));}).join('');};

将生成长度为第一个/调用字符串的随机字母数字字符串

我想这会对你有用:

函数makeid(长度){let result=“”;const characters=‘EFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvxyz0123456789’;常量字符长度=字符长度;让计数器=0;while(计数器<长度){result+=characters.charAt(Math.floor(Math.random()*charactersLength));计数器+=1;}返回结果;}console.log(makeid(5));

功能性方法。只有在应用程序的其他部分可以利用功能先决条件时,这个答案才实用。表演可能是垃圾,但写起来非常有趣。

//功能先决条件常量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'))
])

玩得开心。让我知道你喜欢/学习什么^_^