Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript change for loop variable from within the loop

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?

like image 471
Patrick Avatar asked Jun 26 '26 13:06

Patrick


1 Answers

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.

like image 54
dudewad Avatar answered Jun 29 '26 04:06

dudewad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!