gpt4 book ai didi

javascript - 无法定位JavaScript程序中无限循环的原因

转载 作者:行者123 更新时间:2023-12-03 07:38:14 25 4
gpt4 key购买 nike

我正在编写一个程序,用于娱乐和练习,它接受用户输入并猜测输入值。然而,在我的测试环境中,我无法接受提示,因此我使用数字 5,并且我还使用 debug 而不是 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;

最佳答案

//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);
};
};

关于javascript - 无法定位JavaScript程序中无限循环的原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35519786/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com