js生成8位随机字符串密码(大小写字母,数字,特殊字符否包含)

最近做了一个功能,随机生成一个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));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值