一、优势
1、只需传入几个参数即可
2、密码可以自己设置长度、有无特殊字符、有无数字、大小写字母
二、源码
main.js
class generatePassword{
/**
* @param {Boolean} lower-是否有小写字母
* @param {Boolean} upper-是否有大写字母
* @param {Boolean} number-是否有数子
* @param {Boolean} symbol-是否有特殊字符
* @param {Number} length-密码长度
* @param {Element} input_dom -输入框元素
* @param {Object} -配置
***/
constructor(lower,upper,number,symbol,length,input_dom,{lostr_tim,lostr_type,sever_time}){//sever_time储存时长
this.lower=lower
this.upper=upper
this.number=number
this.symbol=symbol
this.length=length
this.input_dom=input_dom
this.paswod=''
}
init(){this.handler()}
handler(){
let paswod_arr=[]
let str_arr=''
let a='abcdefghigkmnlopqrstuvwxyz'
let A='ABCDEFGHIJKMNLOPQRSTUVWXYZ'
let te='!@#$%^&*(){}[]=<>/,.'
let num='1234567890'
let chek=[]
if( this.lower){str_arr+=a
chek.push(/[a-z]/)}
if(this.upper){str_arr+=A
chek.push(/[A-Z]/)}
if(this.number){str_arr+=num
chek.push(/[0-9]/)}
if(this.symbol){
str_arr+=te
chek.push(te)
}
str_arr=str_arr.split('')
let key=true
while(key){
paswod_arr=[]
for(let zero=0,l=this.length;zero<l;zero+=1){
paswod_arr.push(str_arr[Math.floor(Math.random()*str_arr.length)])
}
key=false
chek.forEach((item)=>{
if(item.toString().indexOf('/')==0){
if(!item.test(paswod_arr.join(''))){
key = true
}
}
else{
let ker=true
item.split('').forEach((d)=>{
ker = paswod_arr.join('').indexOf(d)>=0?false:true
})
if(ker){
key=true
}
}
})
}return paswod_arr.join('')
}
rander(){
this.input_dom.value= this.handler()
}
}
二、示例
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text" id="in" />
<input type="button" value="生成随机密码" onclick="creat_password()">
</body>
<script src="./main.js"></script>
<script>
function creat_password(){
let ne=new generatePassword(true ,true ,true,true,14,document.querySelector('#in'),{})
ne.rander()
}
</script>
</html>
效果