我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
当前回答
仅仅一个简单的map或reduce实现就足够了:
const charset: string =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const random1: string = [...Array(5)]
.map((_) => charset[Math.floor(Math.random() * charset.length)])
.join("");
const random2: string = [...Array(5)]
.reduce<string>(
(acc) => acc += charset[Math.floor(Math.random() * charset.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('');};
将生成长度为第一个/调用字符串的随机字母数字字符串
我使用var randId='rand'+new Date().getTime();
随机unicode字符串
此方法将返回一个随机字符串,其中包含任何受支持的unicode字符,这不是OP要求的100%,而是我想要的:
function randomUnicodeString(length){
return Array.from({length: length}, ()=>{
return String.fromCharCode(Math.floor(Math.random() * (65536)))
}).join('')
}
根本原因
这是谷歌搜索“随机字符串javascript”时的最高结果,但OP只要求a-zA-Z0-9。
简单方法:
function randomString(length) {
let chars = [], output = '';
for (let i = 32; i < 127; i ++) {
chars.push(String.fromCharCode(i));
}
for (let i = 0; i < length; i ++) {
output += chars[Math.floor(Math.random() * chars.length )];
}
return output;
}
如果您想要更多或更少的字符,请将“127”更改为其他字符。
这不是一个完美的解决方案,但它应该奏效。如果出现任何错误,请增加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(密码);