利用javascript如何随机生成一定位数的密码
程序员文章站
2022-07-06 20:50:12
前言
本文主要给大家介绍了关于利用javascript随机生成一定位数密码的相关内容,分享出来供大家参考学习,下面话不多少,来一起看看详细的介绍吧。
需求
随机生成一...
前言
本文主要给大家介绍了关于利用javascript随机生成一定位数密码的相关内容,分享出来供大家参考学习,下面话不多少,来一起看看详细的介绍吧。
需求
随机生成一定位数的密码,有最小个数和最大个数,必须包含数字、大小写字母,和特殊字符比如(- _ #);
代码
function createpassword(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(createpassword(8,15));
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对的支持。