js Tag Syntax Usage Details

  • 2021-11-29 05:52:24
  • OfStack

Directory 1. Introduction to tag statements 2. Use of tag statements

Foreword:

We often use recursion in daily development, break , continue , return Wait for the statement to change the position where the program runs, in fact, in the JavaScript Label statements are also provided to mark the specified block of code for jumping to the specified location. This article records how to use the label statement under 1.

1. Introduction to tag statements

A label statement is used to label a statement. The label can have the same name as a variable. It is an independent syntax element (neither a variable nor a type), and its function is to identify the "tagged statement ( labeled statement ) "is equivalent to a locator for jumping to anywhere in the program, with the following syntax:

label: statement

For example:


    hello:console.log("hello")


Label statements can change the execution flow of programs, similar to break , continue And return . Among them break And continue It can be used with tag 1.

2. The tag statement uses the

(1) The tag statement is used in conjunction with break to jump out of a specific loop


    let num = 0;
    mylabel:
    for (let i = 0; i < 10; i++) {
      for (let j = 0; j < 10; j++) {
        if (i == 5 && j == 5) {
          break mylabel;
        }
        num++;
      }
    }
    console.log(num); // 55


In this example, outermost The label identifies the first for Statement. Normally, each loop executes 10 times, which means that num++ Statement is executed 100 times, and at the end of the loop console.log The result should be 100. But, break Statement brings 1 variable, which is the label to exit to. Adding tags not only makes break Exiting the inner loop (using the variable j) also exits the outer loop (using the variable i). When i and j are both equal to 5, the loop stops executing, and at this time num The value of is 55.

(2) Label statements are used in conjunction with continue


    let num = 0;
    mylabel:
    for (let i = 0; i < 10; i++) {
      for (let j = 0; j < 10; j++) {
        if (i == 5 && j == 5) {
          continue mylabel;
        }
        num++;
      }
    }
    console.log(num); // 95


continue Statement forces the loop to continue, but not the inner loop, but the outer loop. Executes when i and j are both equal to 5 continue Skip to the outer loop and continue execution, resulting in less execution of the inner loop by 5 times. As a result, num Equal to 95.

Summary:

Combining tag statements with break , continue It can implement complex logic, but it is also prone to errors. Note that tags should use descriptive text and not be nested too deeply.


Related articles: