1

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?

4 Answers4

6

continue 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;
            }
        }
    }
}
OhleC
  • 2,581
  • 12
  • 26
1

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.

zfrisch
  • 7,744
  • 1
  • 18
  • 31
1

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!

Andrew Ridgway
  • 563
  • 2
  • 9
0

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;

}
Tyler Roper
  • 20,529
  • 6
  • 30
  • 51