最近做了一个功能,随机生成一个8位字符串密码:
要求必须包含大写字母、小写字母、数字和特殊字符,下面和大家分享下
首先我们要了解下 ASCLL码
js提供两个方法:
分别将ASCLL码转为字符:String.fromCharCode();将字符转为ASCLL码:'a'.charCodeAt();
// 查表得知:
// 数字0~9对应的ASCII码值是 48-57
// 大写字母A-Z对应的ASCII码值是 65-90
// 小写字母a-z对应的ASCII码值是 97-122
// 特殊字符对应的ASCII码的值是33-47 58-64
const getPassword = (legnth) => {
// 定义一个空数组保存我们的密码
let 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);
// 转为字符串返回
return passArrItem.join('');
}
// 输出我们获取到的包含大写、小写字母和数字的8位字符串密码
console.log(getPassword(8));