3

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?

3
  • Why can't you just assign it the value you want? It's just another variable after all. Just make sure you don't set it in such a way that you'll infinitely loop. Commented Jan 1, 2014 at 21:03
  • 1
    I have a feeling that this may be an X/Y Problem. Commented Jan 1, 2014 at 21:05
  • I see that I could've reassigned it now. And yes this is one question I'm looking an answer to in order to solve a bigger problem. Commented Jan 1, 2014 at 21:23

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I don't want to exit the loop after I change the i value though. Is there another way of doing this? I'll go read function scope and look.
nvm I see why it would exit the loop imeediately. Because 15000 < 100.
1

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 */
}

6 Comments

You should add some condition to avoid the infinite loop,
@cookiemonster definitely this will not be the complete loop he must be doing something inside the loop
Yeah, just wanted to make sure that some beginner out there didn't run the code and freeze their browser. ;-)
Yea I'm doing something else within the loop, but I just got stuck on this part.
share your complete loop and tell us what you want to do
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.