Question

I have a for loop like so

for (var i = 0; i < 100; i += 4) {
    // code with i;
}

I would like to change the value of i to a certain value from within the loop. I am aware you could use continue to change the value of i after evaluating the final-expression, but what if I wanted to change the value of i to something more specific like 40?

Here's one of my attempts

loop:
for (var i = 0; i < 100; i += 4) {
    for (var i = 0; i <= 40; i++) {
        continue loop;
    }
}

Is there a better way of doing this?

Was it helpful?

Solution

Just change i directly:

for (var i = 0; i < 100; i += 4) {
    i = 15000;
}

This would exit the loop immediately, but you could do whatever you wanted.

You should read up on function scope to understand how this stuff works. For loops are bit different from functions in that they're a language construct but the same theory of scope holds true.

OTHER TIPS

The scope of increment variable is always available inside the loop block, this allows you to access increment variable inside the loop block.

for (var i = 0; i < 100; i += 4) {
    if (condition)  i = 40 ;
    /* put any condition to avoid the infinite loop and continue with your rest of code */
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top