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

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


当前回答

这样怎么样:Date.now().toString(36)不是很随意,但每次调用它时都很短且非常独特。

其他回答

这不是一个完美的解决方案,但它应该奏效。如果出现任何错误,请增加Uint8Array()构造函数中给定的值。此方法的优点是它使用getRandomValues()方法生成加密的强随机值。

var array=新Uint8Array(20);crypto.getRandomValues(数组);var arrayEncoded=btoa(String.fromCharCode(…array)).split(“”);var arrayFiltered=arrayEncoded.filter(值=>{开关(值){大小写“+”:return false;大小写“/”:return false;case“=”:return false;违约:返回true;}});var password=arrayFiltered.slice(0,5).join('');console.log(密码);

紧凑型

var array=新Uint8Array(20);crypto.getRandomValues(数组);var password=btoa(String.fromCharCode(…array)).split(“”).filter(值=>{回来['+','/','=']includes(value);}).切片(0,5).连接('');console.log(密码);

像这样扩展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));

带有es6排列运算符的更新版本:

[…数组(30)].map(()=>Math.random().toString(36)[2]).join(“”)

30是一个任意数字,您可以选择所需的任何令牌长度36是可以传递给numeric.toString()的最大基数,表示所有数字和a-z小写字母2用于从如下所示的随机字符串中选择第三个索引:“0.mfbiohx64i”,我们可以取0之后的任何索引。

生成任意数量的十六进制字符(例如32):

(function(max){let r='';for(let i=0;i<max/13;i++)r+=(Math.random()+1).toString(16).substring(2);return r.substring(0,max).toUpperCase()})(32);

一个衬垫[a-z]:

String.fromCharCode(97 + Math.floor(Math.random() * 26))