JavaScript knowledge points sorting - process control

1, Process control

In the process of a program execution, the execution order of each code has a direct impact on the result of the program. Many times, we need to control the execution order of the code to realize the functions we want to complete

Three main structures of process control

  • Sequential structure
  • Branching structure
  • Cyclic structure

2, Sequential process control

Execute in sequence according to the sequence of codes

3, Branching structure

In the process of executing code from top to bottom, different path codes are executed according to different conditions (the process of executing one or more codes), so as to get different results

JS language provides two branch structure statements:

  • if statement
  • switch Statements

3.1 if statement

3.1.1 if syntax structure

    if(Conditional expression){
        //Execute statement
    }
    xxx
    // Execution idea if the conditional expression result in if is true, execute the execution statement in braces
    // If the result of the conditional expression is false, the statement in braces will not be executed, and the code after the if statement will be executed

3.1.2 execution process

3.1.3 case exercise - simple age verification case

Pop up the input box and ask the user to enter the age. If the age is greater than or equal to 18 years old, the age verification is successful and the time limit for teenagers in the game is lifted

    var age = prompt('Please enter your age:');
    if(age >= 18){
        alert('Lifting the game duration limit for teenagers');
    }

3.2 if else statement (double branch statement)

3.2.1 grammatical structure

    // 1. Grammatical structure
    if(Conditional expression){
        // Execute statement 1
    } else {
        // Execute statement 2
    }
    // 2. Execution idea if the expression structure is true, execute statement 1, otherwise execute statement 2

3.2.2 execution process

3.2.3 case exercise - judging leap years

Receive the year entered by the user. If it is a leap year, the leap year will pop up, otherwise it is a normal year

Leap years are those that can be divided by 4 and cannot be divided by 100

    var year = prompt('Please enter the year:');
    if(year % 4 == 0 && year % 100 !=0){
        alert('The year you entered is a leap year');
    } else {
        alert('The year you entered is a normal year');
    }

3.3 if else if (multi branch statement)

3.3.1 grammatical structure

    // 1. Grammatical structure
    if (Conditional expression 1){
        // Statement 1;
    } else if (Conditional expression 2) {
        // Statement 2;
    } else if (Conditional expression 3) {
        // Statement 3;
    } else {
        // The last sentence;
    }

3.3.2 execution process

3.3.3 precautions

(1) Multiple branch statements or multiple choices. Only one statement can be executed at last

(2) Theoretically, there can be any number of conditions in else if

(3) else if has a space in the middle

3.3.4 case exercise - judging achievement cases

Receive the score entered by the user and output the corresponding grade letters A, B, C and D according to the score

  1. Above 85 points (inclusive), output: A
  2. 70 points (included) ~ 85 points (excluded), output: B
  3. 60 min (included) ~ 70 min (excluded), output: C
  4. Below 60 minutes (excluding), output: D
    var score = prompt('Please enter a score:');
    if (score >= 85) {
        alert('Your grade is: A');
    } else if (score >= 70) {
        alert('Your grade is: B');
    } else if (score >= 60) {
        alert('Your grade is: C');
    } else {
        alert('Your grade is: D');
    }

3.4 # ternary expression

A formula composed of ternary operators becomes a ternary expression

3.4.1 grammatical structure

// Conditional expression? Expression 1: expression 2

3.4.2 implementation ideas

If the result of the conditional expression is true, the value of expression 1 is returned; If the expression result is false, the value of expression 2 is returned

3.4.3 case exercise - number 0

The user inputs a number. If the number is less than 10, it will be supplemented with 0 in front, such as 01 and 05. If the number is greater than 10, it does not need to be supplemented, such as 18

    var time = prompt('Please enter a 0~59 A number between');
    var result = time < 10 ? '0' + time : time;
    alert(result);

3.5 switch statement

The switch statement is also a multi branch statement, which is used to execute different code based on different conditions. When you want to set a series of options for a specific value for a variable, you can use switch

3.5.1 grammatical structure

    switch(expression) {
        case value1:
            Execute statement 1; // Code to execute when equal to value1
            break;
        case value2:
            Execute statement 2; // Code to execute when equal to value2
            break;
        ... // Multiple branches can be set
        default:
            Execute the last statement; // Code to execute when not equal to value
    }

3.5.2} implementation ideas

Use the value of our expression to match the option value after case

If it matches, execute the statements in the case

If there is no match, execute the statement in default

3.5.3 precautions

(1) We usually write expressions as variables

(2) When the value of the variable in the expression matches the value in the case, it is congruent, and the value must be consistent with the data type

(3) Break if there is no break in the current case, you will not exit the switch, but continue to execute the next case

3.5.4 case exercise - query fruit

The user enters a fruit in the pop-up box. If there is, the price of the fruit will pop up. If there is no fruit, the "no fruit" will pop up

    var fruit = prompt('Please enter the fruit you want to query:');
    switch (fruit) {
        case 'a mandarin orange':
            alert('The price of oranges is 5 yuan/Jin');
            break;
        case 'Apple':
            alert('The price of oranges is 3 yuan/Jin');
            break;
        default:
            alert('No such fruit');
    }

3.6 difference between switch and if else

  1. In general, their two statements can be replaced with each other
  2. The switch... Case statement usually deals with the case where the value is determined by comparison, while the if... else... Statement is more flexible and is often used to judge the range (greater than or equal to a certain range)
  3. The switch statement executes the conditional statement of the program directly after judging the condition, which is more efficient. if... else statements have several conditions, you have to judge how many times
  4. When there are few branches, the execution efficiency of if... else statement is higher than that of switch statement
  5. When there are many branches, the execution efficiency of switch statement is higher and the structure is clearer

4, Cyclic structure

4.1 purpose of circulation

In practical problems, there are many regular repetitive operations, so in order to complete such operations in the program, it is necessary to repeat some statements

4.2 circulation in JS

There are three main types of circular statements:

  • for loop
  • while Loop
  • do... while loop

4.3 for loop

4.3.1 grammatical structure

The for loop is mainly used to loop some code several times, which is usually related to counting

Syntax structure:

    for(initialize variable; Conditional expression; Operation expression){
        // Circulatory body
    }
  • Initialization variable: a common variable declared with var
  • Conditional expression: it is the code used to decide whether to continue the execution of each loop
  • Operation expression: it is the code executed at the end of each cycle

4.3.2 execution process of for loop

  1. First, execute the counter variable var i = value, but this sentence is only executed once in for
  2. Go to value1 < = I < = Value2 to judge whether the conditions are met. If the conditions are met, execute the loop body, and exit the loop if the conditions are not met
  3. Finally, execute i + +. i + + is the code written separately. The first round is over
  4. Start the second round, and then execute value1 < = I < = Value2. If the conditions are met, execute the loop body, and exit the loop if the conditions are not met

4.3.3 case exercise - student achievement

The user is required to input the number of classes, then input the scores of each student in turn, and finally print out the total score and average score of the class

4.3.4 double for loop execution process

Nested loop refers to the syntax structure of defining a loop statement in a loop statement

    var num = prompt("Please enter the total number of people in the class:");
    var sum = 0;
    var average = 0;
    for (var i = 1; i <= num; i++){
        var score = prompt('Please enter the number' + i + 'Student grades');
        sum = sum + parseFloat(score);
    }
    average =sum / num;
    alert('Total grade of class:' + sum + '||' + 'Class average:' + average);

4.3.5 double for loop syntax structure

   for (Initialization variable of outer layer; Conditional expression of outer layer; Operation expression of outer layer){
        for (Initialization variable of inner layer; Conditional expression of inner layer; Operation expression of inner layer){
            // Execute statement
        }
    }

4.3.6 case exercise - print 99 multiplication table

    var str = '';
    for (var i = 1; i <= 9; i++){ // Outer loop control rows
        for (var j = 1; j <= i; j++){ // Inner layer loop controls the number of each line j < = I
            str += i + 'x' + j + '=' + i * j;
        }
        str += '\n';
    }
    console.log(str);

4.4 while loop

4.4.1 while loop syntax structure

    while (Conditional expression) {
        // Circulatory body
    }
  • Execution idea: when the result of the conditional expression is true, execute the loop body, otherwise exit the loop
  • There should also be counters and initialization variables
  • There should also be an operation expression to complete the update of the counter and prevent dead circulation

4.4.2 case exercises

Calculate the sum of all integers between 1 and 100

    var sum = 0;
    var i = 1;
    while (i <= 100){
        sum += i;
        i++
    }
    console.log(sum);

4.5 do while cycle

The do... While statement is actually a variant of the while statement. The loop will execute the code block once, and then judge the conditional expression. If the condition is true, the loop body will be executed repeatedly, otherwise exit the loop

4.5.1 do while loop syntax structure

    do {
        //Circulatory body
    } while (Conditional expression)
  • Execution idea: different from while, do while executes the loop body first, and then judges the conditions. If the result of the conditional expression is true, continue to execute the loop body, otherwise exit the loop
  • Note: the do... while loop statement executes the loop body at least once

4.5.2 case practice

Calculate the sum of all integers between 1 and 100

    var sum = 0;
    var i = 1;
    do {
        sum += i;
        i++
    } while (i <= 100)
    console.log(sum);

4.6 continue keyword

The continue keyword is used to immediately jump out of this loop and continue the next loop (the code after continue in the body of this loop will be executed less than once)

4.6.1 case practice

Find the sum of integers between 1 and 100, except that they can be divided by 7

    var sum = 0;
    for (var i = 1; i <= 100; i++){
        if (i % 7 == 0){
            continue;
        }
        sum += i;
    }
    console.log(sum);

4.7 break keyword

The break keyword is used to immediately jump out of the entire loop (the end of the loop)

Keywords: Javascript Front-end

Added by shivers on Fri, 11 Feb 2022 15:40:40 +0200