首页 > web前端 > js教程 > 正文

javascript随机生成一定位数的密码代码教程

小云云
发布: 2018-02-03 13:30:15
原创
1605 人浏览过

随机生成一定位数的密码,有最小个数和最大个数,必须包含数字、大小写字母,和特殊字符比如(- _ #);本文主要和大家介绍了关于利用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));
登录后复制

相关推荐:

vue实现记住密码到cookie的方法

jquery手势密码插件详解

玩转jQuery实现注册会员时密码强度提示信息功能

以上是javascript随机生成一定位数的密码代码教程的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!