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

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


当前回答

这是我的方法(使用TypeScript)。

我决定写另一个响应,因为我没有看到任何使用现代js和干净代码的简单解决方案。

const DEFAULT_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

function getRandomCharFromAlphabet(alphabet: string): string {
  return alphabet.charAt(Math.floor(Math.random() * alphabet.length));
}

function generateId(idDesiredLength: number, alphabet = DEFAULT_ALPHABET): string {
  /**
   * Create n-long array and map it to random chars from given alphabet.
   * Then join individual chars as string
   */
  return Array.from({length: idDesiredLength}).map(() => {
    return getRandomCharFromAlphabet(alphabet);
  }).join('');
}

generateId(5); // jNVv7

其他回答

递归解决方案:

function generateRamdomId (seedStr) {
const len = seedStr.length
console.log('possibleStr', seedStr , ' len ', len)
if(len <= 1){
    return seedStr
}
const randomValidIndex  = Math.floor(Math.random() * len)
const randomChar = seedStr[randomValidIndex]
const chunk1 = seedStr.slice(0, randomValidIndex)
const chunk2 = seedStr.slice(randomValidIndex +1)
const possibleStrWithoutRandomChar = chunk1.concat(chunk2)

return randomChar + generateRamdomId(possibleStrWithoutRandomChar)

}

你可以用你想要的种子,如果你不想,不要重复字符。实例

generateRandomId("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") 

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

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

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

像这样的东西应该有用

function randomString(len, charSet) {
    charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var randomString = '';
    for (var i = 0; i < len; i++) {
        var randomPoz = Math.floor(Math.random() * charSet.length);
        randomString += charSet.substring(randomPoz,randomPoz+1);
    }
    return randomString;
}

使用默认字符集[a-zA-Z0-9]调用或发送您自己的:

var randomValue = randomString(5);

var randomValue = randomString(5, 'PICKCHARSFROMTHISSET');

Math.random不适合这种情况

服务器端

使用节点加密模块-

var crypto = require("crypto");
var id = crypto.randomBytes(20).toString('hex');

// "bb5dc8842ca31d4603d6aa11448d1654"

生成的字符串将是您生成的随机字节的两倍长;编码为十六进制的每个字节是2个字符。20字节将是40个十六进制字符。


客户端

使用浏览器的加密模块crypto.getRandomValues-

通过crypto.getRandomValues()方法,可以获得加密的强随机值。作为参数给出的数组用随机数填充(在其密码意义上是随机的)。

//dec2hex::整数->字符串//即0-255->“00”-“f”功能dec2hex(dec){return dec.toString(16).padStart(2,“0”)}//generateId::整数->字符串函数生成器ID(len){var arr=新Uint8Array((len||40)/2)window.crypto.getRandomValues(arr)return Array.from(arr,dec2hex).join(“”)}console.log(generateId())//“82defcf324571e70b0521d79cce2bf3ffccd69”console.log(generateId(20))//“c1a050a4cd1556948d41”

分步控制台示例-

> var arr = new Uint8Array(4) # make array of 4 bytes (values 0-255)
> arr
Uint8Array(4) [ 0, 0, 0, 0 ]

> window.crypto
Crypto { subtle: SubtleCrypto }

> window.crypto.getRandomValues()
TypeError: Crypto.getRandomValues requires at least 1 argument, but only 0 were passed

> window.crypto.getRandomValues(arr)
Uint8Array(4) [ 235, 229, 94, 228 ]

对于IE11支持,您可以使用-

(window.crypto || window.msCrypto).getRandomValues(arr)

有关浏览器覆盖范围,请参阅https://caniuse.com/#feat=getrandomvalues


客户端(旧浏览器)

如果您必须支持旧浏览器,请考虑像uuid这样的东西-

const uuid = require("uuid");
const id = uuid.v4();

// "110ec58a-a0f2-4ac4-8393-c866d813b8d1"

例如,如果你想要一个随机的DNA序列,你可以循环遍历一个项目数组并递归地将它们添加到字符串变量中:

功能随机DNA(len){len=长度||100var nuc=新阵列(“A”、“T”、“C”、“G”)变量i=0变量n=0s=“”而(i<=len-1){n=数学楼层(Math.random()*4)s+=努克[n]我++}返回s}console.log(随机DNA(5));