欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

利用javascript如何随机生成一定位数的密码

程序员文章站 2022-05-13 16:06:31
...
这篇文章主要给大家介绍了关于利用javascript如何随机生成一定位数的密码的相关资料,文中给出了详细的js示例代码,对大家的学习或者工作具有一定的参考学习价值,对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));

以上就是本篇文章的所有内容,希望对大家学习提供到帮助。

相关推荐:

Javascript将图片的绝对路径转换为base64编码

javascript基于定时器实现进度条功能实例

JavaScript实现多重继承实例详解

以上就是利用javascript如何随机生成一定位数的密码的详细内容,更多请关注其它相关文章!