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
}
添加回答
举报