I basically just want to print numbers a list of numbers a skip multiples of 3. I got it to work but the initial way i tried it did not work and i do not understand why, just need someone to please explain why it doesn't work and goes into an infinite loop.
This is the problem, why does it go into an infinite loop? I am clearly missing a key concept about code, if someone could help thanks.
var i = 0;
while (i <= 10) {
if (i % 3 == 0) {
continue;
}
document.write( i + "</br>");
i++;
}
I know you can do it this way.
while (i <= 10)
{
if (i % 3 != 0) {
document.write("Number is " + i + "<br />");
}
i++
}
continue
jumps to the next iteration and doesnt complete the rest of your code in the while
. So i
is not being incremented but rather staying as 0 becuase you wrote continue
before incrementing the i
. so therefore it is in an endless loop, it is always less than 10
If we ignore the code producing the output and look only at the code checking and modifying i
, it might become a little more clear why it's not working. It also helps to format our code for extra clarity.
var i = 0;
while (i <= 10) {
if (i % 3 == 0) {
continue;
}
i++;
}
i = 0
.i <= 10
is true
. Enter the loop.i % 3 == 0
is true
. Enter the if
block.continue;
. Go straight to the top of the while
loop again. Do not pass i++;
. Do not collect 1
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.