Maybe this is a dumb question but is there a way to return to the top of a loop?
Example:
for(var i = 0; i < 5; i++) {
if(i == 3)
return;
alert(i);
}
What you'd expect in other languages is that the alert would trigger 4 times like so:
alert(0); alert(1); alert(2); alert(4);
but instead, the function is exited immediately when i is 3. What gives?
-
4Could you give an example of 'other languages'?Jakub Konecki– Jakub Konecki2010年10月13日 19:13:01 +00:00Commented Oct 13, 2010 at 19:13
-
1What languages are you thinking of where returning in the middle of a loop makes the loop continue? It's not so in any language I know.Chuck– Chuck2010年10月13日 19:14:35 +00:00Commented Oct 13, 2010 at 19:14
-
2C# does not continue the loop - once you execute the 'return' statement, the function exits immediately, just as it does in javascript. C# also uses the 'continue' statement for the execution flow you are trying to accomplish.JeremyDWill– JeremyDWill2010年10月13日 21:06:39 +00:00Commented Oct 13, 2010 at 21:06
2 Answers 2
Use continue instead of return.
Example: http://jsfiddle.net/TYLgJ/
for(var i = 0; i < 5; i++) {
if(i == 3)
continue;
alert(i);
}
If you wanted to completely halt the loop at that point, you would use break instead of return. The return statement is used to return a value from a function that is being executed.
EDIT: Documentation links provided by @epascarello the comments below.
- Docs for
continue: https://developer.mozilla.org/en/JavaScript/Reference/Statements/continue - Docs for
return: https://developer.mozilla.org/en/JavaScript/Reference/Statements/return
3 Comments
For what it's worth, you can also label them:
OUTER_LOOP: for (var o = 0; o < 3; o++) {
INNER_LOOP: for (var i = 0; i < 3; i++) {
if (o && i) {
continue OUTER_LOOP;
}
console.info(o, ':', i);
}
}
outputs:
0 : 0
0 : 1
0 : 2
1 : 0
2 : 0