Created
April 5, 2013 08:24
-
-
Save badsyntax/5317545 to your computer and use it in GitHub Desktop.
Using Javascript labels to break out of a nested loop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Break out of a nested loop when both indexes are equal to 1 | |
// It's a stupid example, but demonstrates how to use labels | |
// Traditional (alternatively we could adjust the value of 'i' to break the outer loop) | |
var iteration1 = 0; | |
var found = false; | |
for (var i = 0; i < 3; i++) { | |
for (var j = 0; j < 3; j++) { | |
iteration1++; | |
if (i === 1 && j === 1) { | |
found = true; | |
break; | |
} | |
} | |
if (found) { | |
break; | |
} | |
} | |
console.log(iteration1); // 5 | |
// Using labels | |
var iteration2 = 0; | |
top: for (var i = 0; i < 3; i++) { | |
for (var j = 0; j < 3; j++) { | |
iteration2++; | |
if (i === 1 && j === 1) { | |
break top; | |
} | |
} | |
} | |
console.log(iteration2); // 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment