I have the following code:
for (var i in players) {
for (var x in players[i].bullets) {
for (var y in xpBoosts) {
if (something === true) {
// do something
continue;
}
}
}
}
What will the continue statement do? Will it cycle the innermost for loop or the outermost?
Is there any way I can get the continue statement to cycle through to the next bullet?
I have the following code:
for (var i in players) {
for (var x in players[i].bullets) {
for (var y in xpBoosts) {
if (something === true) {
// do something
continue;
}
}
}
}
What will the continue statement do? Will it cycle the innermost for loop or the outermost?
Is there any way I can get the continue statement to cycle through to the next bullet?
Share Improve this question asked Nov 6, 2018 at 21:22 user9085934user9085934 4-
3
Have you tried using
console.log
to figure it out? – Callam Commented Nov 6, 2018 at 21:24 - I'll try that, thanks for the tip – user9085934 Commented Nov 6, 2018 at 21:25
- 1 maybe a dupe? – Nina Scholz Commented Nov 6, 2018 at 21:25
- developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – ksav Commented Nov 6, 2018 at 21:25
4 Answers
Reset to default 12continue
terminates the current iteration of the loop it's in. To terminate the iteration of another loop, use it with labels:
for (var i in players) {
bullets: for (var x in players[i].bullets) {
for (var y in xpBoosts) {
if (something === true) {
// do something
continue bullets;
}
}
}
}
In your particular code continue
doesn't do anything.
continue
is a keyword that will quit the current iteration of the loop and carry on with the next.
as an example:
for (i = 1; i <= 10; i++) {
if (i == 5) continue;
console.log(i);
}
You'll notice that 5
is not printed to the console. When the conditional check is proven true, it continues onto the next iteration without performing the rest of the code in the block.
By default, continue
and break
apply to the innermost loop. In your particular code, it will continue this loop:
for (var y in xpBoosts) {
However, this behavior can be customized through labels. For example:
outerLoop:
for (var i = 0; i < someVal; i++){
middleLoop:
for (var j = 0; j < someOtherVal; j++){
innerLoop:
for (var k = 0; k < yetAThirdVal; k++){
continue;//skip to next iteration of innerLoop
continue innerLoop;//skip to next iteration of innerLoop
continue middleLoop;//skip to next iteration of middleLoop
continue outerLoop;//skip to next iteration of outerLoop
}
}
}
Hope this helps!
EDIT: I'll leave my answer here, but I much prefer ohlec's answer.
continue
only moves on to the next iteration of the innermost for
loop.
You could have a variable that is initialized as false
for each bullet. You can then mark this to true
if you continue the inside loop.
for (var x in players[i].bullets) {
var skipThisBullet = false;
for (var y in xpBoosts) {
if (something === true) {
// do something
skipThisBullet = true;
continue;
}
}
if (skipThisBullet) continue;
}