js随机生成密码(有3种类型的)

本文介绍了如何使用JavaScript编写一个函数来生成随机密码。包括创建一个js文件包含密码生成逻辑,并在需要的页面导入并调用该函数,例如:`createPassword(6, 6)`用于生成6位数字和字母组成的密码。" 87938943,7680100,TCP连接的三次握手与四次挥手详解,"['网络协议', 'TCP/IP', '通信机制', '网络连接']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 写一个js文件

// 随机密码,数字,字母下划线,大小写都有
export function complexPsw(min, max) {
  // 可以生成随机密码的相关数组
  var num = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
  var english = ['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']
  var ENGLISH = ['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']
  var special = ['-', '_', '#']
  var config = num.concat(english).concat(ENGLISH).concat(special)

  // 先放入一个必须存在的
  var arr = []
  arr.push(getOne(num))
  arr.push(getOne(english))
  arr.push(getOne(ENGLISH))
  arr.push(getOne(special))

  // 获取需要生成的长度
  var len = min + Math.floor(Math.random() * (max - min + 1))

  for (var i = 4; i < len; i++) {
    // 从数组里面抽出一个
    arr.push(config[Math.floor(Math.random() * config.length)])
  }

  // 乱序
  var newArr = []
  for (var j = 0; j < len; j++) {
    newArr.push(arr.splice(Math.random() * arr.length, 1)[0])
  }

  // 随机从数组中抽出一个数值
  function getOne(arr) {
    return arr[Math.floor(Math.random() * arr.length)]
  }

  return newArr.join('')
}
console.log(complexPsw(6,18))   //  最少6位,最大18位

// 随机六位数字密码
export function createPassword() {
  var Num = ''
  for (var i = 0; i < 6; i++) {  //  想要几位就写几,我需要6位,所以我写的6
    Num += Math.floor(Math.random() * 10)
  }
  return Num
}
console.log(createPassword())   // 六位随机数字

// 随机六位数密码,包含字母大小写和数字
export const randomWord = () => {
  let code = ''
  for (var i = 0; i < 6; i++) {
    var type = getRandom(1, 3)
    switch (type) {
      case 1:
        code += String.fromCharCode(getRandom(48, 57))// 数字
        break
      case 2:
        code += String.fromCharCode(getRandom(65, 90))// 大写字母
        break
      case 3:
        code += String.fromCharCode(getRandom(97, 122))// 小写字母
        break
    }
  }
  return code
}
function getRandom(min, max) {
  return Math.round(Math.random() * (max - min) + min)
}

export default randomWord   // 我这里只暴露出去了我需要的一种

2. 在需要的页面使用(例子)

import createPassword from ‘./utils/createPassword.js’
createPassword(6, 6),

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值