1 回答

TA貢獻1772條經驗 獲得超8個贊
與其在事后更改密碼,不如通過確保密碼滿足所有約束從一開始就正確生成密碼。
我已經使用了您的代碼片段來生成一個獨立的函數makeSecurePassword(),該函數接受多個參數:userLength, askLowerCase, askUpperCase, askNumerals, askSpecial。它返回請求的密碼userLength,僅包含請求的字符類型。它使用你的randChar()輔助函數。
var securePassword = makeSecurePassword( 10, true, true, true, true );
console.log(securePassword);
// Return a random character from passwordCharacters:
function randChar(passwordCharacters) {
return passwordCharacters.charAt(Math.floor(Math.random() * passwordCharacters.length));
}
function makeSecurePassword( userLength, askLowerCase, askUpperCase, askNumerals, askSpecial ) {
const lowCaseArr = "abcdefghijklmnopqrstuvwxyz";
const upCaseArr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const numeralArr = "1234567890";
const specialArr = "!@#$%^&*";
var password = [];
// Decide which chars to consider:
charArray = [];
if ( askLowerCase ) {
charArray.push( lowCaseArr );
}
if ( askUpperCase ) {
charArray.push( upCaseArr );
}
if ( askNumerals ) {
charArray.push( numeralArr );
}
if ( askSpecial ) {
charArray.push( specialArr );
}
let x = 0; // index into charArray
for ( var i=0; i < userLength; i++ ) {
var a = charArray[x]; // Which array of chars to look at
// Insert at random spot:
password.splice( password.length, 1, randChar( a ) );
// Pick next set of chars:
if ( ++x >= charArray.length ) {
x = 0; // Start with the first set of chars if we went past the end
}
}
return password.join(''); // Create a string from the array of random chars
}
添加回答
舉報