为什么我的 JavaScript Do-While 循环没有带来我想要的结果?



这段代码让我很头疼。我是JavaScript的新手我只是在学习一些概念,你的知识会有很大帮助。下面给出了代码和输出的详细信息。如果你有解决这个问题的办法,请回答这个问题。谢谢!

//These are my variables
var candy= 10;
var cookies= 20;
var x= 20;
var y= 30;
var g= 1;
//While Loop
while (1 > 10){
console.log ("x + y=50")
}//this won't run at all because 1<10 will never be true, I am 
trying to avoid infinity loops
while (g<=5) {
console.log("The number is " + g )
g++;
}/*if it was '<' it would be an infinity loop or we can just break 
the loop. 
output:
The number is 1
The number is 2
The number is 3.... All the way up to 5
*/
//Do-While Loop
do {
console.log("This is a do-while loop")
} while(candy < 9 && cookies >= x)
/*This will execute once even though both the conditions are 
false, it's just how do-while loops were made*/

//This where the problem comes in
do{
console.log("The other number is " + g)
g++;
} while(g<=5)
/*output: The other number is 6
I thought 6 is greater than 5? Why is it bringing such an output 
yet the condition is g<=5?
I was expecting:
The other number is 1
The other number is 2.... All the way up to 5
*/
let g = 1
while (g<=5) {
console.log("The number is " + g )
g++;
}
//Until g is 5 add one to g, this means that g is 6 here
console.log(g)
do{
console.log("The other number is " + g)
g++;
} while(g<=5)
// a do while loop executes once before the condition is checked

我检查了你的代码,发现了问题。

while (g<=5) {
console.log("The number is " + g )
g++;
}

之后,g已经是5了所以当这个出现

do{
console.log("The other number is " + g)
g++;
} while(g<=5)

循环将只运行一次,因为g不低于5。如果像这样修改代码。它会工作得很好

var g=1;
do{
console.log("g" + g);
g++;
}while(g<=5)

只是删除前循环代码改变g

在涉及g的第一个循环中,检查这个条件:(g<=5)。这意味着当g大于5时循环结束,对吧?

while (g<=5) {
console.log("The number is " + g )
g++;
}

g = 1→g++→g = 2

g = 2→g++→g = 3

g = 3→g++→g = 4

g = 4→g++→g = 5

g=5 (g仍然等于5,所以条件满足)->g++→g = 6

g=6 (g现在大于5,所以你的条件不满足。你不要再循环了。不管怎样,g=6,因为你用g++加了进去循环的前一次迭代)

当你执行下一个循环时,它是一个do-while。这意味着在迭代之后检查条件。

do{
console.log("The other number is " + g)
g++;
} while(g<=5)

话虽如此,实际情况是:

您打印"另一个数字是6"因为从上一次循环的最后一次迭代开始,g是6

你将g增加到7

你检查条件:g=7是负的还是等于5?不。——比;循环停止

您可以尝试在每一步中调试和计算g的值。

另外,请记住g是在之外声明的循环,所以它的作用域是"全局"的。这意味着该值不会"重置"。在每一个新的循环。这就是为什么你得不到你想要的:

另一个号码是1

另一个数字是2....一直到5

相关内容

  • 没有找到相关文章

最新更新