如何在 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>
廣告