Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to break from nested loops in JavaScript?

What's the best way to break from nested loops in Javascript?

//Write the links to the page. for (var x = 0; x < Args.length; x++) {    for (var Heading in Navigation.Headings)    {       for (var Item in Navigation.Headings[Heading])       {          if (Args[x] == Navigation.Headings[Heading][Item].Name)          {             document.write("<a href=\""                 + Navigation.Headings[Heading][Item].URL + "\">"                 + Navigation.Headings[Heading][Item].Name + "</a> : ");             break; // <---HERE, I need to break out of two loops.          }       }    } } 
like image 531
Gary Willoughby Avatar asked Oct 08 '08 14:10

Gary Willoughby


People also ask

How do I break out of nested loops in javascript?

The break statement, which is used to exit a loop early. A label can be used with a break to control the flow more precisely. A label is simply an identifier followed by a colon(:) that is applied to a statement or a block of code.

How do you break a loop in nested?

Using break in a nested loop In a nested loop, a break statement only stops the loop it is placed in. Therefore, if a break is placed in the inner loop, the outer loop still continues. However, if the break is placed in the outer loop, all of the looping stops.

How do you break a loop in javascript?

The break statement breaks out of a switch or a loop. In a switch, it breaks out of the switch block. This stops the execution of more code inside the switch. In in a loop, it breaks out of the loop and continues executing the code after the loop (if any).

Does Return break nested for loop javascript?

return always exits the current function. If you need to exit a loop you should be using break which terminates the current loop, label or switch statement. Thank you!


2 Answers

Just like Perl,

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             }         }     } 

as defined in EMCA-262 section 12.12. [MDN Docs]

Unlike C, these labels can only be used for continue and break, as Javascript does not have goto.

like image 128
ephemient Avatar answered Sep 22 '22 04:09

ephemient


Wrap that up in a function and then just return.

like image 32
swilliams Avatar answered Sep 21 '22 04:09

swilliams