我编写了一个JavaScript类,其中包含四个静态变量,其中包含最终密码可能包含的不同类型的字符。该类包含四个getter函数,它们从这四个变量中返回一个随机字符。在一个单独的函数中,我尝试创建密码。不幸的是,最终的密码似乎并不包含完全随机的字符。相同的字符经常重复出现
我仔细看了看我的随机函数,但它似乎很好。我希望你知道为什么密码最终会如此相似,例如AAAh^8或bSS+5S
class Password{
static lowerCase = "abcdefghijklmnopqrstuvwxyz";
static upperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static numbers = "0123456789";
static symbols = "!@#$%^&*()_+~\`|}{[]:;?><,./-=";
length = document.getElementById("passwordLength").value;
getKey = [this.upperCase, this.lowerCase, this.num, this.symbol]
get upperCase(){
return Password.upperCase[Math.floor(Math.random() * Password.upperCase.length)]
}
get lowerCase(){
return Password.lowerCase[Math.floor(Math.random() * Password.lowerCase.length)]
}
get num(){
return Password.numbers[Math.floor(Math.random() * Password.numbers.length)]
}
get symbol(){
return Password.symbols[Math.floor(Math.random() * Password.symbols.length)]
}
password = ""
}
function createPassword(){
const newPass = new Password;
for (var i=0; i<newPass.length; i++){
key = newPass.getKey[Math.floor(Math.random() * newPass.getKey.length)]
newPass.password += key
console.log("Random Key Run " + i + ": " + key)
}
console.log("Final Password: " + newPass.password)
}
createPassword()
正如@ decize所说,您实际上是在getKey
初始化器中预先选择了4个不同的字符。
如果你不太喜欢getter,你可能会有更好的时间,例如
function pick(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
class PasswordGenerator {
static lowerCase = "abcdefghijklmnopqrstuvwxyz";
static upperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static numbers = "0123456789";
static symbols = "!@#$%^&*()_+~\`|}{[]:;?><,./-=";
static classes = [
PasswordGenerator.lowerCase,
PasswordGenerator.upperCase,
PasswordGenerator.numbers,
PasswordGenerator.symbols,
];
getChar() {
const cls = pick(PasswordGenerator.classes);
return pick(cls);
}
}
function createPassword() {
const generator = new PasswordGenerator();
let password = "";
for (var i = 0; i < 8; i++) {
const key = generator.getChar();
password += key;
console.log(`Random Key Run ${i}: ${key}`);
}
console.log("Final Password: " + password);
}
createPassword();
我还擅自将不应该是Password
状态的东西移出PasswordGenerator
类。