最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript change for loop variable from within the loop - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question asked Jan 1, 2014 at 21:02 PatrickPatrick 1,4282 gold badges19 silver badges37 bronze badges 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. – cookie monster Commented Jan 1, 2014 at 21:03
  • 1 I have a feeling that this may be an X/Y Problem. – cookie monster 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. – Patrick Commented Jan 1, 2014 at 21:23
Add a ment  | 

2 Answers 2

Reset to default 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.

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 */
}
发布评论

评论列表(0)

  1. 暂无评论