您好,登錄后才能下訂單哦!
前言
本文主要給大家介紹了關于利用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));
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。