[英]I can't figure out why I'm getting infinite loop
I'm in the process of learning this language and I was asked by my teacher to write some code.我正在学习这门语言,我的老师让我写一些代码。 Checked for all other posts about it and couldn't find the answer and I just don't understand why I'm getting infinite loop since the condition seems clear (to me at least haha): num1 has to be different from num2.
检查了所有其他关于它的帖子,但找不到答案,我只是不明白为什么我会得到无限循环,因为条件似乎很清楚(至少对我来说哈哈):num1 必须与 num2 不同。 The code is supposed to keep making the question in num2 until the user types the same number as num1.
该代码应该继续在 num2 中提出问题,直到用户键入与 num1 相同的数字。
var num1 = Number(prompt("Digite um número"))
console.log("Fight!")
arrayFinal = []
var num2 = Number(prompt("Que número o jogador 1 escolheu?"))
for (num1; num2 !== num1; num2) {
arrayFinal.push(num2)
console.log("O número chutado foi: ", num2)
if (num2 > num1) {
console.log("MISS! O número é menor!")
} else if (num2 < num1) {
console.log("MISS! O númenor é maior!")
}
}
console.log("GAME OVER! O jogador 2 venceu! O número de tentativas foi: " +
(arrayFinal.lenght + 1))
您想多次询问用户num2
,因此它的prompt
应该在循环中。
Your loop starts at num1
.您的循环从
num1
开始。 It also says that it will continue looping as long as num2 !== num1
.它还说只要
num2 !== num1
它将继续循环。 But at the end of line 6, you just simply put num2
, which does nothing to change num1.但是在第 6 行的末尾,您只需简单地放置
num2
,它不会改变 num1。 So, as long as num1
was previously unequal to num2
, it will always be unequal to num2
and thus make the loop infinite.所以,只要
num1
之前不等于num2
,它就永远不等于num2
,从而使循环无限。
You can declare num2
as null outside the loop, then do the prompting inside the loop.您可以在循环外将
num2
声明为 null,然后在循环内进行提示。 That way, when num2
equals num1
, num2 !== num1
returns false
, and the loop will stop looping after that iteration.这样,当
num2
等于num1
, num2 !== num1
返回false
,并且循环将在该迭代后停止循环。 Otherwise, it will continue looping and prompting again and again... until the user inputs the same number as num1
, then it will stop looping after the current iteration.否则,它将继续循环并一遍又一遍地提示……直到用户输入与
num1
相同的数字,然后在当前迭代后停止循环。
Also, Take lines 8-13 in the original code out of the loop, so that it does not get repeated as the code prompts repeatedly.另外,把原代码中的第8-13行去掉循环,这样就不会因为代码反复提示而重复了。
var num1 = Number(prompt("Digite um número"));
console.log("Fight!");
arrayFinal = [];
for (num1; num2 !== num1; num2) {
var num2 = Number(prompt("Que número o jogador 1 escolheu?")); //dont forget
semicolon
arrayFinal.push(num2);
console.log("O número chutado foi: ", num2);
if (num2 > num1) {
console.log("MISS! O número é menor!");
} else if (num2 < num1) {
console.log("MISS! O númenor é maior!");
}
}
console.log("GAME OVER! O jogador 2 venceu! O número de tentativas foi: " +
(arrayFinal.length + 1));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.