在 JavaScript 中,帶標籤和不帶標籤的 break 語句之間的區別是什麼?


沒有標籤的 break 語句

break 語句用於早退迴圈,跳出包圍的大括號。 break 語句退出迴圈。 

示例

讓我們來看一個在 JavaScript 中使用 break 語句而不使用標籤的示例 −

即時演示

<html>
   <body>
     
      <script>
 
         var x = 1;
         document.write("Entering the loop<br /> ");
       
         while (x < 20) {
            if (x == 5){
               break; // breaks out of loop completely
            }
            x = x + 1;
            document.write( x + "<br />");
         }
       
         document.write("Exiting the loop!<br /> ");
 
      </script>
     
   </body>
 </html>

帶標籤的 break 語句

標籤用於控制程式流程,即假設在巢狀 for 迴圈中使用它來跳轉到內部或外部迴圈。你可以嘗試執行以下程式碼,使用標籤和帶有 break 語句來控制流程,−

示例

即時演示

<html>
   <body>
     
      <script>
            document.write("Entering the loop!<br /> ");
            outerloop: // This is the label name
       
            for (var i = 0; i < 5; i++) {
               document.write("Outerloop: " + i + "<br />");
               innerloop:
               for (var j = 0; j < 5; j++) {
                  if (j > 3 ) break ; // Quit the innermost loop
                  if (i == 2) break innerloop; // Do the same thing
                  if (i == 4) break outerloop; // Quit the outer loop
                  document.write("Innerloop: " + j + " <br />");
               }
            }
       
            document.write("Exiting the loop!<br /> ");
      </script>
     
   </body>
 </html>

更新時間:2020 年 6 月 12 日

442 次瀏覽

開啟你的 職業生涯

透過完成課程認證

開始
廣告
© . All rights reserved.