Thursday, 10 May 2018

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(" + Navigation.Headings[Heading][Item].URL + "\">"
+ Navigation.Headings[Heading][Item].Name + "
: ");
break; // <---HERE, I need to break out of two loops.
}
}
}
}

Answer



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.


No comments:

Post a Comment

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...