Process control
In the execution process of a program, the execution sequence of each code has a direct impact on the results of the program. In many cases, we need to control the execution sequence of the code to achieve the function we want to complete.
There are three structures for process control:
- Sequential structure
- Branching structure
- Loop structure
Sequential flow control
Sequential flow control is the simplest and most basic flow control. There is no specific syntax structure, and the program will be executed in sequence according to the sequence of the code.
The branch process controls the IF statement
When executing code from top to bottom, different paths of code are executed (the process of executing multiple code choices) depending on different conditions, resulting in different results.
- If statement
- Single branch statement
//1 if(conditional expression){// Execute the statement } //2 //3. Code experience if(3>5){ alert('hellow world! '); } Copy the code
- Double branch statement
//1 if(conditional expression){// Execute statement 1 } else{ // Execute statement 2 } //2 //3. Code validation Copy the code
- Multi-branch statement
//1 ifConditional expression1) {//语句1 } else ifConditional expression2) {//语句2 } else{ //语句3 } //2 //3. Code validation Copy the code
- Single branch statement
Ternary expression
A formula consisting of three operators is called a ternary expression. A simplified version of if-else.
//1
// Conditional expression? Expression 1: expression 2
//2
//3. Code validation
Copy the code
Branch flow controls switch statements
Switch is used when setting options for a variable with a specific set of values.
switch(expression){caseValue1: executes the statement1;
break;
caseValue2: executes the statement2;
break; .default: Executes the last statement; }Copy the code
- Value after case must be congruent.
- In real development, expressions are often written as variables.
- If there is no break in the current case, the switch is not exited and the next case continues.
Switch and if else if.
- In general, two statements can be substituted for each other.
- switch… Case statements typically handle cases where case is a certain value, whereas if… else… Statements are more flexible and are often used for large range judgments (greater than or equal to a range)
- Switch directly executes the conditional statement of the program after judging the condition, which is more efficient. And the if… Else statements have several conditions, so you have to judge them as many times as you want.
- Switch statements execute more efficiently and have a clearer structure when there are many branches.