一、生成指定位数的随机数
/**
* 随机生成字符串
* @param len 指定生成字符串长度
*/
function getRandomString(len = 32) {
const chars = 'abcdefghjklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789';
let str = '';
for (let i = 0; i < len; i++) {
const randomIndex = Math.floor(Math.random() * chars.length);
str += chars[randomIndex];
}
return str;
}
二、生成指定位数的随机密码
// 数字0~9对应的ASCII码值是 48-57
// 大写字母A-Z对应的ASCII码值是 65-90
// 小写字母a-z对应的ASCII码值是 97-122
// 特殊字符对应的ASCII码的值是33-47 58-64
getPassword(legnth){
// 定义一个空数组保存我们的密码
const passArrItem = [];
// 定义获取密码成员的方法
const getNumber = () => Math.floor(Math.random() * 10); // 0~9的数字
const getUpLetter = () => String.fromCharCode(Math.floor(Math.random() * 26) + 65); // A-Z
const getLowLetter = () => String.fromCharCode(Math.floor(Math.random() * 26) + 97); // a-z
const getCode = () => String.fromCharCode(Math.floor(Math.random() * 15) + 33) || String.fromCharCode(Math.floor(Math.random() * 7) + 58)
// 将获取成员的方法保存在一个数组中方便用后面生成的随机index取用
const passMethodArr = [getNumber, getUpLetter, getLowLetter,getCode];
// 随机index
const getIndex = () => Math.floor(Math.random() * 4);
// 从0-9,a-z,A-Z,以及特殊字符中随机获取一项
const getPassItem = () => passMethodArr[getIndex()]();
// 不多解释
Array(legnth - 4).fill('').forEach(() => {
passArrItem.push(getPassItem());
})
const confirmItem = [getNumber(), getUpLetter(), getLowLetter(), getCode()];
// 加上我们确认的四项,从而使生成的密码,大写字母、小写字母、数字和特殊字符至少各包含一个
passArrItem.push(...confirmItem);
// 转为字符串返回
const passStr = passArrItem.join('')
console.log('随机密码',passStr);
return passStr;
},