我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
我想要一个5个字符的字符串,由从集合[a-zA-Z0-9]中随机选取的字符组成。
用JavaScript实现这一点的最佳方法是什么?
当前回答
快速和改进的算法。不保证统一(见注释)。
function getRandomId(length) {
if (!length) {
return '';
}
const possible =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let array;
if ('Uint8Array' in self && 'crypto' in self && length <= 65536) {
array = new Uint8Array(length);
self.crypto.getRandomValues(array);
} else {
array = new Array(length);
for (let i = 0; i < length; i++) {
array[i] = Math.floor(Math.random() * 62);
}
}
let result = '';
for (let i = 0; i < length; i++) {
result += possible.charAt(array[i] % 62);
}
return result;
}
其他回答
这是肯定的
<script language="javascript" type="text/javascript">
function randomString() {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var string_length = 8;
var randomstring = '';
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
}
document.randform.randomfield.value = randomstring;
}
</script>
随机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 getRandomStrings(length) {
const value = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const randoms = [];
for(let i=0; i < length; i++) {
randoms.push(value[Math.floor(Math.random()*value.length)]);
}
return randoms.join('');
}
但如果您在ES6中寻找一个较短的语法:
const getRandomStrings = length => Math.random().toString(36).substr(-length);
生成包含aA zZ和0-9字符集合的随机字符串。只需使用长度参数调用此函数。
所以要回答这个问题:generateRandomString(5)
generateRandomString(length){
let result = "", seeds
for(let i = 0; i < length - 1; i++){
//Generate seeds array, that will be the bag from where randomly select generated char
seeds = [
Math.floor(Math.random() * 10) + 48,
Math.floor(Math.random() * 25) + 65,
Math.floor(Math.random() * 25) + 97
]
//Choise randomly from seeds, convert to char and append to result
result += String.fromCharCode(seeds[Math.floor(Math.random() * 3)])
}
return result
}
生成不带数字的字符串的版本:
generateRandomString(length){
let result = "", seeds
for(let i = 0; i < length - 1; i++){
seeds = [
Math.floor(Math.random() * 25) + 65,
Math.floor(Math.random() * 25) + 97
]
result += String.fromCharCode(seeds[Math.floor(Math.random() * 2)])
}
return result
}
最简单的方法是:
(new Date%9e6).toString(36)
这将基于当前时间生成5个字符的随机字符串。示例输出为4mtxj或4mv90或4mwp1
这样做的问题是,如果您在同一秒内调用它两次,它将生成相同的字符串。
更安全的方法是:
(0|Math.random()*9e6).toString(36)
这将生成一个4或5个字符的随机字符串,总是不同的。示例输出类似于30jzm或1r591或4su1a
在这两种方式中,第一部分生成一个随机数。.toString(36)部分将数字转换为它的base36(字母十进制)表示形式。