无法在 JavaScript 程序中找到无限循环的原因

unable to locate cause of infinite loop in JavaScript program

我正在编写一个用于娱乐和练习的程序,它接受用户输入并猜测输入值。但是在我的测试环境中我无法接受提示,所以我使用数字 5 代替,并且我还使用调试而不是 console.log。我找不到无限循环开始的位置,据我所知,它只是对一个数组进行计数,直到到达字符串“5”,循环应该停止。我需要第二双眼睛看这个,Stack Overflow。谢谢!

//Password Cracker

//"userPassword" will not be read by the computer, instead it will be guessed and reguessed.
var userPassword = 5 + ''

//the following variable contains an array of all the possible characters that can be present.
var possibleCharacters = ['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','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','1','2','3','4','5','6','7','8','9','0'];

//the computer's current guess.
var computerGuess = null;

//establishes that the computer has not correctly guessed the password, will be changed when password is discovered.
var correctGuess = null;

//the following variable keeps track of how many guesses it takes for the computer to crack the password.
var totalGuesses = 0;

//the following function checks if the current guess of the computer matches the password inputted by the user.
var checkPassword = function(passwordGuess) {

    if(passwordGuess === userPassword) {
        debug("Your password is " + computerGuess + ". Gotta do better to fool me!");
    }else{
        debug("Guessing again.");
    };

};

//the loop that should stop when the password has been guessed correctly. the variable 'i' counts up through the strings in the array.
while(computerGuess !== userPassword) {

    for(var i = 0; i < 61; i++) {
        computerGuess = possibleCharacters[i];
        checkPassword(computerGuess);
        };
    };

end;

如果您想进行暴力破解,请在此处查看此算法:

https://codereview.stackexchange.com/questions/68063/brute-force-password-cracker

或google一些"bruteforce javascript algorithm"

干杯

//the loop that should stop when the password has been guessed correctly. the variable 'i' counts up through the strings in the array.
while(computerGuess !== userPassword) {    
    for(var i = 0; i < 61; i++) {
        computerGuess = possibleCharacters[i];
        checkPassword(computerGuess);
    };
};

这是一个无限循环,因为内部循环(for 循环)总是遍历所有字符,所以 computerGuess 在最后是 '0'。因此,while 条件始终满足。一旦你猜到了正确的密码,你就可以通过打破 for 循环来解决这个问题:

while(computerGuess !== userPassword) {
    for(var i = 0; i < 61 && computerGuess !== userPassword; i++) {
        computerGuess = possibleCharacters[i];
        checkPassword(computerGuess);
    };
};