编程语言
首页 > 编程语言> > 在JavaScript中打破嵌套循环的最佳方法是什么?

在JavaScript中打破嵌套循环的最佳方法是什么?

作者:互联网

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

解决方法:

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

如EMCA-262第12.12节中的定义. [MDN Docs]

与C不同,这些标签只能用于continuebreak,因为Javascript没有goto.

标签:nested-loops,javascript,loops,break
来源: https://codeday.me/bug/20190915/1805377.html