【发布时间】:2016-02-20 06:00:59
【问题描述】:
我正在编写一个有趣和练习的程序,它接受用户输入并猜测输入值。但是在我的测试环境中我无法接受提示,所以我使用数字 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;
【问题讨论】:
-
请edit您的问题直接显示代码。无论如何,您的 for 循环在到达正确的 pass 字符时不会停止,因此当 for 结束时,while 循环条件仍然为真。当密码“单词”只能是一个字符时,为什么还要嵌套循环?
-
在每个 while 循环中,您将遍历 for 循环中的所有 61 个(不应该是 62 个吗?)可能性...最后,computerGuess 将是第 61 个可能性('9 ') 当 while 循环检查是否找到它时......所以,它永远不会被发现......你需要停止 for 循环 - 事实上,你甚至不需要 while 循环......如果你设置了密码到“9”,我敢打赌它不会无限循环
-
@Ageonix - 这是有效的 JS。
-
不太可能是问题所在,但
end;是什么? -
此外,您所拥有的只是线性搜索的过于模糊的实现。您可能需要研究
Array.prototype.indexOf方法来简化您的代码,并减少出错的机会。
标签: javascript infinite-loop infinite