首頁  >  文章  >  web前端  >  javascript隨機產生一定位數的密碼代碼教學

javascript隨機產生一定位數的密碼代碼教學

小云云
小云云原創
2018-02-03 13:30:151621瀏覽

隨機產生一定位數的密碼,有最小個數和最大個數,必須包含數字、大小寫字母,和特殊字元例如(- _ #);本文主要和大家介紹了關於利用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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn