admin管理员组文章数量:1327524
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
2 Answers
Reset to default 3Just 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 */
}
本文标签: Javascript change for loop variable from within the loopStack Overflow
版权声明:本文标题:Javascript change for loop variable from within the loop - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742193332a2430617.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论