Js生成随机数/随机字符串的5种方法
Js生成随机数/随机字符串的5种方法:
方法1:使用randomString
function randomString(e) {
e = e || 8; // e表示长度,默认8位
let t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678",
a = t.length,
n = "";
for (i = 0; i < e; i++){
n += t.charAt(Math.floor(Math.random() * a));
}
return n;
}
console.log(randomString(6));
方法2:使用随机数
function GetRandomNum(Min,Max){
let Range = Max - Min;
let Rand = Math.random();
return(Min + Math.round(Rand * Range));
}
let num = GetRandomNum(10000,999999);
console.log(num);方法3:对数组字符集进行随机选取
let str = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
function generateMixed(n) {
let res = "";
for(let i = 0; i < n ; i ++) {
let id = Math.ceil(Math.random()*35);
res += str[id];
}
return res;
}
console.log(generateMixed(6));
方法4:生成随机数转成36进制,再截取部分
//Math.random() 生成随机数字, eg: 0.123456 //.toString(36) 转化成36进制 : "0.4fzyo82mvyr" //.slice(-8); 截取最后八位 : "yo82mvyr" let str = Math.random().toString(36).slice(-6); console.log(str);
方法5:对字符串集合随机排列,随机输出指定的长度
function randomString(length) {
let str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
let result = '';
for (let i = length; i > 0; --i){
result += str[Math.floor(Math.random() * str.length)];
}
return result;
}
console.log(randomString(6));
原文链接:https://www.jb51.net/article/187445.htm。侵权联删。
