2. Process control

Posted by divadiva on Tue, 08 Feb 2022 15:59:03 +0100

Statement: all the contents of my front-end learning notes are the learning notes of teacher pink's course on station b. If you want to know more, you can search the following website:

  1. H5C3 + Mobile layout: Dark horse programmer pink teacher front-end introductory video tutorial HTML5+CSS3 + mobile terminal layout flex layout rem layout responsive layout imitation guest blue lake use - simple, interesting and fun
  2. JavaScript series: JavaScript basic syntax - dom/bom-es6-jQuery - data visualization ecarts - including note source code homework, dark horse programmer pink teacher front-end introductory video tutorial (continuous update)

JavaScript process control

1. Introduction to process control

There are three main structures of process control, namely sequence structure, branch structure and loop structure. These three structures represent the execution order of the three codes.

2. Sequential structure

Sequential structure is the simplest and most basic process control in the program. It has no specific syntax structure. The program will execute in sequence according to the sequence of codes. Most codes in the program are executed in this way.

3. Branch 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 statement

3.2 if statement

// If the condition is true, execute the code, otherwise do nothing
if (Conditional expression) {
	// Code statement executed when the condition is satisfied
}
var usrAge = prompt('Please enter your age:');
if(usrAge >= 18){
	alert('Your age is legal. Welcome to the Internet cafe to enjoy your study!');
}

3.3 if else statement (double branch statement)

// If the condition holds, execute the code in if, otherwise execute the code in else
if (Conditional expression) {
	// [if] the condition is true, the code to be executed
} else {
	// [otherwise] executed code
}
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
    alert("This year is a leap year");
} else { // The rest are ordinary years
    alert("This year is a normal year");
}

3.4 if else if statement (multi branch statement)

// Suitable for checking multiple conditions.
if (Conditional expression 1) {
	Statement 1;
} else if (Conditional expression 2) {
	Statement 2;
} else if (Conditional expression 3) {
    Statement 3;
    ....
} else {
	// None of the above conditions holds. Execute the code here
}

3.5 ternary expression

Expression 1 ? Expression 2 : Expression 3;

If expression 1 is true, the value of expression 2 is returned; if expression 1 is false, the value of expression 3 is returned. Simple understanding: it is similar to the abbreviation of if else

var time = prompt('Please enter a 0 ~ 59 A number between');
// Ternary expression? Expression 1: expression 2
var result = time < 10 ? '0' + time : time; // Assign the return value to a variable
alert(result);

3.6 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.

switch(expression){
case value1:
    // Code to execute when expression equals value1
    break;
case value2:
    // Code to execute when expression equals value2
    break;
default:
	// Code to be executed when the expression is not equal to any value
}
  • The keyword switch can be followed by an expression or value in parentheses, usually a variable
  • Keyword case, followed by an expression or value of an option, followed by a colon
  • The value of the switch expression is compared with the value of case in the structure. If there is a matching congruence (= = =), the code block associated with the case will be executed and stopped when a break is encountered, and the code execution of the whole switch statement will end; If the value of all cases does not match the value of the expression, execute the code in default

Note: when executing the statement in the case, if there is no break, continue to execute the statement in the next case.

3.7 difference between switch statement and if else statement

  • In general, their two statements can be replaced with each other
  • 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)
  • 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.
  • When there are few branches, the execution efficiency of if... else statement is higher than that of switch statement. When there are many branches, the execution efficiency of switch statement is higher and the structure is clearer.

4. Circulation structure

Loop purpose: 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

In a program, a group of repeatedly executed statements is called the loop body. Whether it can continue to be executed repeatedly depends on the termination condition of the loop. The statement composed of the loop body and the termination condition of the loop is called a loop statement

In Js, there are three types of circular statements:

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

4.1 for loop

1. Grammatical structure

The for loop is mainly used to loop some code several times, which is usually related to counting. Its syntax structure is as follows:

for(initialize variable; Conditional expression; Operation expression){
	//Circulatory body
}
  • Initialization variable: it is usually used to initialize a counter. This expression can declare a new variable using var keyword. This variable helps us record the number of times.
  • Conditional expression: used to determine whether each cycle can be executed. If the result is true, continue the loop, otherwise exit the loop.
  • Operation expression: the expression to be executed at the end of each loop. It is usually used to update or increment counter variables. Of course, decreasing variables are also possible.

Execution process:

  1. Initialize variables. The initialization operation will be executed only once in the whole for loop.
  2. Execute the conditional expression. If true, execute the loop body statement. Otherwise, exit the loop and the loop ends.
  3. Execute the operation expression, and the first round ends.
  4. At the beginning of the second round, execute the conditional expression directly (no longer initialize the variable). If it is true, execute the loop body statement, otherwise exit the loop.
  5. Continue to execute the operation expression, and the second round ends.
  6. The following is consistent with the second round until the conditional expression is false, ending the whole for loop.

2. Breakpoint debugging

Breakpoint debugging refers to setting a breakpoint in a certain line of the program. When debugging, the program will stop when it runs to this line, and then you can debug step by step. During debugging, you can see the current value of each variable. If there is an error, the error will be displayed when debugging to the wrong code line, and stop.

  • Press F12 in the browser – > sources -- > to find the file to be debugged – > set a breakpoint on a line of the program
  • Watch: monitoring. You can monitor the change of variable value through watch. It is very common.
  • F11: the program executes step by step. Let the program execute line by line. At this time, observe the change of the value of the variable in the watch.

3. Basic operation of for loop

//The for loop repeats the same code
var num = prompt('Please enter the number of times:');
for ( var i = 1 ; i <= num; i++) {
	console.log('Daughter in law, I was wrong~');
}
//The for loop can also repeat different codes, mainly because of the use of counters, which change during each cycle.
// Basic writing method
for (var i = 1; i <= 100; i++) {
	console.log('This man this year' + i + 'Years old');
}
//Because of the existence of the counter in the for loop, we can also repeatedly perform some operations, such as doing some arithmetic operations.
var sum = 0;
for(var i = 1;i <= 100; i++){
	sumNum += i;
}
console.log('1-100 Sum of integers between= ' + sum);

4. for cycle cases

① Pop up the input box and enter the total class number (num)
② Enter the student's score in turn (save score). At this time, we need to use the for loop. The number of pop-up times is related to the total number of students in the class. The conditional expression I < = num
③ Conduct business processing: calculate scores. sum first, then average
④ Pop up results

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

4.2 double for loop

Loop nesting refers to defining the syntax structure of a loop statement in a loop statement. For example, a for loop can be nested in a for loop statement. Such a for loop statement is called double for loop.

1. Grammatical structure

for (Initial of external circulation; Conditions of external circulation; Operation expression of outer loop) {
    for (Initial of internal circulation; Conditions of internal circulation; Inner loop operation expression) {
    	Code to execute;
    }
}
  • The inner loop can be regarded as the statement of the outer loop
  • The execution order of the inner loop should also follow the execution order of the for loop
  • The outer loop is executed once, and the inner loop is executed all times

2. Case analysis

Print 99 multiplication table:

① There are 9 lines in total, but the number of each line is different, so a double for loop is required
② The for loop of the outer layer controls the number of lines i, which can be printed 9 times
③ The inner for loop controls each line of formula j
④ Core algorithm: the number of formulas in each line is exactly the same as the number of lines, J < = I;
⑤ After printing each line, you need to change another line
⑥ Replace the formula with i and j

var str = ''
for (var i = 1; i <= 9; i++) { // Control the number of rows in the outer layer: 9 rows
    for (var j = 1; j <= i; j++) { // j control the number of columns. The number of columns and rows are the same. j < = I
        str += j + " × " + i + " = " + i * j + '\t'; //Note: use string to connect!!
    }
	str += '\n';// Wrap a line after printing
}
console.log(str);

4.3 while loop

while statement can execute a specified piece of code in a loop on the premise that the conditional expression is true, and end the loop until the expression is not true.

The syntax structure of the while statement is as follows:

while (Conditional expression) {
	// Loop body code
}

Implementation idea:
① If the conditional expression is true, the code will be executed first; If false, exit the loop and execute the following code
② Execute loop body code
③ After the execution of the loop body code, the program will continue to judge the execution condition expression. If the condition is still true, the loop body will continue to be executed until the loop condition is false

be careful:
① When using a while loop, you must be aware that it must have exit conditions, otherwise it will become an endless loop
② The difference between the while loop and the for loop is that the while loop can judge more complex conditions, such as user name and password

while (love != 'I love you!') {
	var love = prompt('Do you love me?');
} 
alert('Login successful');

4.4 do while loop

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.
The syntax structure of the do... while statement is as follows:

do {
	// Loop body code - repeats the loop body code when the conditional expression is true
} while(Conditional expression);

Implementation idea:

① Execute the loop body code once first
② Then execute the conditional expression. If the result is true, continue to execute the loop body code. If it is false, exit the loop and continue to execute the following code

Note: execute the loop body first and then judge. We will find that the do... while loop statement will execute the loop body code at least once

do {
	var love = prompt('Do you love me?');
} while (love != 'I love you!')
alert('Login successful');

4.5 cycle summary

  • In JS, there are for, while and do while loops. In many cases, the three loops can be used instead of each other
  • If it is used to count times, it is related to numbers. The three use basically the same, but we prefer to use for
  • while and do... while can make more complex judgment conditions, which is more flexible than the for loop
  • The execution order of while and do... While is different. While is judged first and then executed. Do... While is executed once and then judged
  • The execution times of while and do... While are different. Do... While will execute the loop body at least once, while while while may not execute at all
  • In practical work, we often use the for loop statement, which is more concise and intuitive, so we should focus on learning this

4.6 continue and break keywords

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).

For example, if you eat five steamed stuffed buns and the third one has insects, throw away the third one and continue to eat the fourth and fifth steamed stuffed buns. The code is as follows:

for (var i = 1; i <= 5; i++) {
    if (i == 3) {
        console.log('This steamed stuffed bun has worms. Throw it away');
        continue; // Jump out of this cycle and jump out of the third cycle
    }
	console.log('I'm eating the third' + i + 'Where's a steamed stuffed bun');
}

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

For example, if you eat five steamed stuffed buns, you will find half a bug in the third one, and you won't eat the rest. The code is as follows:

for (var i = 1; i <= 5; i++) {
    if (i == 3) {
        break; // Directly exit the whole for loop and jump to the statement below the whole for
    }
	console.log('I'm eating the third' + i + 'Where's a steamed stuffed bun');
}

5. JavaScript naming specification and syntax format

5.1 identifier naming specification

  • The names of variables and functions must be meaningful
  • Variable names are generally nouns
  • The names of functions are usually verbs

5.2 operator specification

// Leave a space on the left and right sides of the operator
for (var i = 1; i <= 5; i++) {
    if (i == 3) {
        break; // Directly exit the whole for loop and jump to the statement below the whole for
    }
	console.log('I'm eating the third' + i + 'Where's a steamed stuffed bun');
}

5.3 single line note specification

for (var i = 1; i <= 5; i++) {
    if (i == 3) {
        break; // Notice a space in front of a single line comment
    }
	console.log('I'm eating the third' + i + 'Where's a steamed stuffed bun');
}

5.4 other specifications

Topics: Javascript Programming