如何在 JavaScript 中給塊標籤?


塊語句將零個或多個語句分組。在 JavaScript 以外的語言中,它被稱為複合語句。

語法

以下是語法:

{
   //List of statements
}

要給塊新增標籤,請使用以下語法:

Identifier_for_label: {
   StatementList
}

讓我們使用它來編寫帶有 break 語句的程式碼。你可以嘗試執行以下程式碼,使用標籤來控制帶有 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 月 15 日

364 次瀏覽

助力您的 事業

完成課程並獲取認證

立即開始
廣告
© . All rights reserved.