I tried this:
for(i=0;i<5;i++)
{
for(j=i+1;j<5;j++)
{
break(2);
}
alert(1)
};
only to get:
SyntaxError: missing ; before statement
I tried this:
for(i=0;i<5;i++)
{
for(j=i+1;j<5;j++)
{
break(2);
}
alert(1)
};
only to get:
SyntaxError: missing ; before statement
break
doesn't take parameters. There are two workarounds:
Wrap them in a function and call return
Set a flag in the inner loop and break again right after the loop if the flag is set.
You should be able to break to a label, like so:
function foo ()
{
dance:
for(var k = 0; k < 4; k++){
for(var m = 0; m < 4; m++){
if(m == 2){
break dance;
}
}
}
}
Unfortunately you'll have to set a flag or use labels (think old school goto statements)
var breakout = false;
for(i=0;i<5;i++)
{
for(j=i+1;j<5;j++)
{
breakout = true;
break;
}
if (breakout) break;
alert(1)
};
The label approach looks like
end_loops:
for(i=0;i<5;i++)
{
for(j=i+1;j<5;j++)
{
break end_loops;
}
alert(1)
};
edit: label incorrectly placed. also see http://www.devguru.com/Technologies/ecmascript/quickref/break.html and http://www.daaq.net/old/javascript/index.php?page=js+exiting+loops&parent=js+statements
Break 1st loop:
for(i=0;i<5;i++)
{
for(j=i+1;j<5;j++)
{
//do something
break;
}
alert(1);
};
Break both loops:
for(i=0;i<5;i++)
{
var breakagain = false;
for(j=i+1;j<5;j++)
{
//do something
breakagain = true;
break;
}
alert(1);
if(breakagain)
break;
};
You need to name your outer loop and break that loop, rather than your inner loop - like this.
outer_loop:
for(i=0;i<5;i++) {
for(j=i+1;j<5;j++) {
break outer_loop;
}
alert(1);
}
loop1:
for (var i in set1) {
loop2:
for (var j in set2) {
loop3:
for (var k in set3) {
break loop2; // breaks out of loop3 and loop2
}
}
}
code copied from http://stackoverflow.com/questions/183161/best-way-to-break-from-nested-loops-in-javascript/183197#183197
Please search before posting a question. The link was the FIRST related question I saw on the left side of this page!
function myFunction(){
for(var i = 0;i < n;i++){
for(var m = 0;m < n;m++){
if(/*break condition*/){
goto out;
}
}
}
out:
//your out of the loop;
}
Use function for multilevel loops - this is good way:
function find_dup () {
for (;;) {
for(;;) {
if (done) return;
}
}
}