我需要产生一个随机的六个字符基数36字符串。
我使用以下两个包,但它并不总是返回这六个字符。
const seed = require('random-seed').create();
const bases = require('bases')
console.log(bases.toBase36(seed(10000000, 99999999)))发布于 2022-11-09 20:19:38
我试过的最简单的方法是:
randstr = _ => Math.floor(2176782335*Math.random()).toString(36);
randstr();或者更容易记住:
randstr = _ => Math.floor(parseInt('zzzzzz',36)*Math.random()).toString(36);
randstr();这是取Base36值zzzzzz;乘以0≤n≤1在000000和zzzzzz之间得到一个值;然后转换回Base36。
更广泛地说:
randstr = len => (
Math.floor(Math.pow(36,len)*Math.random())
.toString(36)
);
randstr(6);大约2%的情况下,由于前导零,这些解决方案可能会使字符串比len短。如果这有关系的话:
randstr = len => (
Math.floor(Math.pow(36,len)*(1+Math.random()))
.toString(36)
.slice(-len)
);
randstr(6);说这些话,虽然做一些奇怪的事情更有趣,比如:
randstr => len => (
'1234567890qwertyuiopasdfghjklzxcvbnm'
.repeat(len)
.split('')
.sort( _ => Math.random()-.5 )
.join('')
.slice(-len)
);
randstr(6);太慢了。
令人失望的是,忽略数学方法,只使用字符串就更快、更清晰了:
randstr = len => {
let x = '';
while (len--)
x += '1234567890qwertyuiopasdfghjklzxcvbnm'[Math.floor(36*Math.random())];
return x;
};
randstr(6);发布于 2021-07-08 07:29:48
您可以使用这样的方法来获取随机字符。
const crypto = require("crypto");
console.log(crypto.randomBytes(36).toString('hex'));crypto内置于NodeJs中。
https://stackoverflow.com/questions/68297232
复制相似问题