Relearning front end JavaScript (2) JavaScript statements

Time:2021-4-21

This article mainly introduces the statements in JavaScript, including several loop statements and conditional statements.

Conditional statements in JavaScript

1、 Definition
  Conditional statementWhen the condition is satisfied, execute a statement
2Conditional statements in JavaScript
  1) if…else if … else: when the specified condition is true, the if statement will execute a section of statement. If the condition of else if is not satisfied, the statement in else will be executed

const a = 2;
    if (a === 0) {
        console . log (' A is ',  a );
    } else if (a === 1) {
        console . log (' A is ',  a );
    } else {
        console . log (' A is ',  a );
    }

  2) Switch… Case statement: Evaluates an expression, matches the value of the expression with the case clause, and executes the statement associated with the situation.

switch (expression) {
        case value1:
            //  When the result of expression matches value1, execute the statement here
            [break;]
        case value2:
            //When the result of expression matches Value2, execute the statement here
            [break;]
        ...
        case valueN:
            //This statement is executed when the result of expression matches the value n
            [break;]
        [default:
            //If the expression does not match the value above, execute the statement here
            [break;]]
    }

  Syntax analysis:
     A. expression: an expression used to match a case sub statement.
    b . case valueN : Optional , The case clause used to match expression. If the expression matches the given valuen ( Here it is ===) , the statement in the case clause is executed until the switch statement ends or a break is encountered.
     C. default: optional, a default clause; if given, this clause will be executed when the value of expression does not match any case statement.
     D. if break is not added, the code will start from the case statement with the value matched, and then continue to execute the next case statement regardless of whether the value matched or not.
   reference from:
    MDN–switch
  3) Logical operators : && And ||
   &: logical and makes it possible to coordinate two or more expressions. Only when each of these expressions returns true, the whole expression will return true
||: logical or, when any one of two or more expressions returns true, the entire expression will return true.

    let a = 0 || 1;
    a && fn();

  4) Ternary operator : is the only operator in JavaScript that uses three operands. A condition is followed by a question mark (?). If the condition is true, expression a following the question mark will be executed; expression a is followed by a colon (:). If the condition is false, expression B following the colon will be executed. This operator is often used as a simple form of if statement.

    let a = true;
    let b = a ? 1 : 0;

Loop statements in JavaScript

1、 Definition
  Loop statement: complete some repetitive tasks.
2For loop
For loop: used to create a loop that contains three optional expressions enclosed in parentheses, separated by semicolons, followed by a statement executed in the loop.

    for (initializer; exit-condition; final-expression) {
        // code to run
    }

  A. Syntax analysis:
     1) in the for loop, there are three items separated by semicolons
    2 ) The first project is the initializer ( initializer ), It’s usually a variable set to a number , It is incremented to count the number of times the loop runs , It is sometimes called a count variable
     3) the second item is exit condition, which is used to define when the loop stops
     4) the third item is the final expression, which is usually used to increase (decrease) the counter variable to make it closer to the exit condition value
      5) curly braces that contain code blocks are used to run the code every time a loop
   reference from: MDN — loop bar code

  B. Execution sequence
      1) the first time: execute the initializer to determine whether the initialization variable meets the exit condition. If it meets the exit condition, exit the loop; otherwise, execute the content in the code block to execute the final condition and increase or decrease the initialization variable
      2) follow up steps: judge whether the initialization variable meets the exit condition, if so, exit the loop; otherwise, execute the content in the code block / — > / execute the final condition, and increase or decrease the initialization variable
  notes: when using let for variable declaration, the initializer step is performed every time.

  C. Optimization of for loop
   when the number of cycles is a variable, the length can be stored to avoid reading the length of the array once every cycle, which is not cost-effective

    for (var i = 0, len = arr.length; i < len; i++) {
        // code to run
    }

  D. What are the following results? Why? How to achieve the desired results?

const liList =  document.querySelectorAll ('li '); // there are three li
    for (var i = 0, len = liList.length; i < len; i++) {
        liList[i].onclick = function() {
            console.log(i);
        }
    }

   results : Console output 3 3
   reason: in the for loop, the variable declared by VaR is a global variable, and the same variable is involved in accumulation or decrement each time, so the variable can also be accessed outside the for loop. JS code is executed sequentially, from top to bottom, when it is executed to element binding events(liList[i].onclick), the value of I is the value in the current loop; when you click the corresponding element to trigger an event, because the for loop has been executed, then I in the function is a global I, that is, I satisfying the exit condition of the for loop, that is, len, that is, 3.
   how to click an element and output its corresponding subscript:
      1) using closure, the variables inside the function are saved in memory

    for (var i = 0, len = liList.length; i < len; i++) {
        liList[i].onclick = (function(i) {
            return function() {
                console.log(i);
            }
        })(i)
    }

two ) Use let to define the block level scope. Variables declared with let in the for loop are only valid in this loop , So I of each cycle is a new variable. The JavaScript engine remembers the value of the last loop , When initializing the variable I of this round , The calculation will be based on the previous round. The for loop sets the part of the loop variable that is a parent scope , The circulatory body is a separate sub scope. ( From http :// es6 . ruanyifeng . com /# do …

    for (let i = 0, len = liList.length; i < len; i++) {
        liList[i].onclick = function () {
            console.log(i);
        }
    }

3) Use const to define the block level scope. The reason why const is not declared in the parent scope is that when a loop is executed to a certain step, the initial variable will be incremented or decremented, and the basic data type declared by const cannot be modified, otherwise an error will be reported.

    for (var i = 0, len = liList.length; i < len; i++) {
        const a = i;
        liList[i].onclick = function () {
            console.log(a);
        }
    }

3while Loop
  while Loop : If a conditional expression is true , Loop executes a specified piece of code , End the loop until that expression is not true.

    while (condition) {
        statement
    }

  A. Syntax analysis:
    1 ) condition : Conditional loop statement , Evaluated before each loop. If the value is true , The statement will be executed. If the evaluation is false , Then jump out of the while loop and execute the following statement
     2) statement: as long as the conditional expression evaluates to true, the statement will always be executed. To execute multiple statements in a loop, you can use block statements ({…}) to wrap multiple statements.

  B. Execution sequence
     judgment conditions ( condition ) Is it satisfied , If not, quit , If satisfied, execute the code ( statement ); Then continue with the process , Until I quit.
Reference from : MDN — while

4Do… While loop
  Do… While loop: creates a loop that executes the specified statement until the condition value is false. Condition is detected after the statement is executed, so the specified statement is executed at least once.

    do {
        statement
    } whild (condition);

  A. Syntax analysis:
     1) statement: a statement executed at least once and re executed each time the condition value is true. To execute multiline statements, use block statements ({…}) to wrap them.
    2 ) condition : An expression that is evaluated each time in a loop. If the condition value is true , Statement will be executed again. When condition value is false , Then jump to do … Statement after while.

  B. Execution sequence
     first execute the code (statement), then judge whether the condition is satisfied, if not, call out the loop, if satisfied, continue to execute. Then continue the process until you exit.
Reference from : MDN — do … whild

4for…in
  for…in: Iterate through the enumerable properties of an object in any order except symbol. for … In is built to traverse object properties and is not recommended with arrays. IE6 support.

//  Variable when object is an object , It is the key ; When the object is an array , It is an index
    for (variable in object){
        statement
    }

    let obj = {a: 1, b: 2};
    for (let i in obj) {
        console.log (i) ; // the key of the object: a B
    }

    let arr = [1, 2, 3];
    for (let i in arr) {
        console.log (i) ; // index of array: 0 1 2
    }

Reference: MDN — for… In

5for…of
  for…of: create an iteration loop on the iteratable objects (including array, map, set, string, typedarray, arguments objects, etc.), call the custom iteration hook, and execute statements for the values of each different attribute. Ie does not support it, edge12 does.

    for (variable of iterable) {
        //statements
    }

Loop control statement:

  continue: skip the current loop and execute the next one
  break: exit the loop immediately.

    for (let i = 0; i < 3; i++) {
        if (i === 1) {
            continue;
        }
        console.log(i);  // 0  2
    }

    for (let i = 0; i < 3; i++) {
        if (i === 1) {
            break;
        }
        console.log(i); // 0
    } 

If the above contents are wrong , I hope you can point out that , thank you.

Recommended Today

Looking for frustration 1.0

I believe you have a basic understanding of trust in yesterday’s article. Today we will give a complete introduction to trust. Why choose rust It’s a language that gives everyone the ability to build reliable and efficient software. You can’t write unsafe code here (unsafe block is not in the scope of discussion). Most of […]