has a direct impact on the result of the execution order of each code. Many times we have to control the execution order of the code to achieve the functions we want to complete.
A brief understanding: flow control is to control us. In what order should the written code be executed to achieve our purpose.
There are three main structures in process control: sequential structure, branch structure and loop structure. These three structures represent the order of code execution.
Sequential structure is the simplest and most basic process control in the program. The codes we wrote before all belong to the sequential structure (that is, executed from top to bottom). It has no fixed syntax structure. The program will follow the order of the code. In order,
. In the process of executing the code from top to bottom, different path codes are executed according to different conditions (the process of selecting one of multiple execution codes), thereby obtaining different results.
1.21 The js language provides two branch structures. Statement
// Execute code if the condition is true, otherwise do nothing
if (conditional expression) {
//Code language for execution when the condition is established == Execute only when the conditional expression is true
}
A statement can be understood as a behavior. Loop statements and branch statements are typical statements. A program consists of many statements. Under normal circumstances, it will be divided into
Statementcode demonstration
one by one
var age=19; if(age>=18){ console.log('You are an adult'); //Output that you are already an adult, because age=19;, if it is greater than 18, the statement in the if will be executed } var age=1; if(age>=18){ console.log('You are an adult'); //Output nothing. age=1;<18, the statement in the if will not be executed, so there is no }
execution process
syntax structure
//If the condition is established, execute the code in if, otherwise execute the code in else
if (conditional expression) {
//Code to be executed that meets the conditions
}else{
//Code that does not meet the conditions for execution
}
Execution process
Code demonstration
var age=prompt('Please enter your age');//User input if(age>=18){ console.log('You can drink now'); }else{ console.log('Sorry, minors can only drink AD calcium'); } //Judge whether the year is a run year var year=prompt('Please enter the year:'); if(year%4==0&&year%100!=0||year%400==0){ alert('The year you entered is a leap year'); }else{ alert('The year you entered is an ordinary year'); }
syntax structure
// Suitable for checking multiple conditions
if (conditional expression) {
Statement 1;
}else if(conditional expression){
Statement 2;
}else if(conditional expression){
Statement 3;
…
}else{
//Execute this code if the above conditions are not met
}
Process control
Code demonstration
//Mini calculator: input two numbers and operation symbols to get the corresponding var yi = +prompt('Please enter the first number'); //Please use addition, subtraction, multiplication and division to implicitly convert to numeric type, or use praseInt (variable) or parsefloat (variable) integers and floating point numbers var fuhao = prompt( 'Please enter operator'); var er = +prompt('Please enter the second number'); if (fuhao == '+') { var shu = yi + er; } else if (fuhao == '-') { var shu = yi - er; } else if (fuhao == '/') { var shu = yi / er; } else if (fuhao == '*') { var shu = yi * er; } else if (fuhao == '%') { var shu = yi % er; } else { alert('Please enter as required:'); } alert(shu);
The switch statement is also a multi-branch statement. It is used to execute different codes based on different conditions. When you want to set a series of specific values for variables, switch switch
(expression) {
case value1:
//The code to be executed when the expression is equal to value1
break;
case value2:
//The code to be executed when the expression is equal to value2
break;
default:
//The code to be executed when the expression is not equal to any value
}
Process control
Code demonstration
var fruit =prompt('Please enter the fruit you want to buy:'); switch(fruit){ case 'apple': alert('The price of apples is: 3.5/catty'); break; case 'lychee': alert('The price of lychees is: 10.5/jin'); break; default: alert('No fruit'); }
Note
The difference between switch statement and if else if statement.
In general, the two statements can be converted into each other.
Switch... case statement usually handles the situation where the case is a comparison to determine the value, while if...else... statement is more Flexible, often used for range judgment (greater than, equal to a certain range).
The switch statement performs conditional judgment and directly executes the conditional statement of the program, which is more efficient. However, if...else...statements have several conditions and must be judged multiple times. .
When there are fewer branches, the execution efficiency of the if...else... statement is higher than that of the switch statement.
When there are many branches, the execution efficiency of the switch statement is higher, and the structure is clearer.
in practical problems, there are many regularities. Repeated operations, so to perform such operations in the program, you must repeatedly execute certain statements.
. In Js, there are three main types of loop statements:
in the program. , a group of statements that are repeatedly executed is called a loop body. Whether it can continue to be executed repeatedly depends on the conditions for loop termination.
The statement composed of the loop body and the loop termination condition is called a loop statement.
Thesyntax structure
of for loop is mainly used Repeating certain code several times, usually related to counting. The statement structure is as follows
for (initialization variable; conditional expression; operation expression) {
//Loop body
}
process control
Code demonstration
for (var i=1;i<=10;i++){ console.log('Do you like me?'); }//Calculate the total score of the class and the average score var num = prompt('Please enter the total number of people in the class') var sum = 0, average = 0; for (var i = 1; i <= num; i++) { var score = prompt('Please enter the score of the ' + i + ' student') //The data taken from prompt is a string and needs to be converted into a number sum += parseInt(score); } average = sum / num; alert('Total score of the class:' + sum); alert('Average score of class:' + sum);//Print 5 hearts in one line for (var i=0;i<=4;i++){ console.log('*'); }
Double-layer for loop (loop nesting)
Loop nesting refers to the grammatical structure of defining a loop statement within a loop statement. For example, nesting a for loop within a for loop. We call such a for loop statement Double-layer for loop
We call the inner loop the inner loop, and the outer loop the outer loop. The outer
loop loops once, and the inner loop is executed from beginning to end.
Code demonstration
// Low-level: 5 rows and 5 columns var str =''; for (var i=0;i<=4;i++){ for (var j=0;j<=4;j++){ str+='*'; } str+='n'; } console.log(str); //Advanced: n rows and n columns var rows = prompt('Please enter the number of rows:'); var cols = prompt('Please enter the number of columns'); var str=''; for (var i = 1; i <= rows; i++) { for (var j = 1; j <= cols; j++) { str+='*'; } str+='n'; } console.log(str); //Print inverted triangle var str=''; for (var i=1;i<=10;i++){ for (var j=i;j<=10;j++){ str+='*'; } str+='n'; } console.log(str); /* 1 ********** 10 2 *********9 3 ********8 4 *******7 5******6 6*****5 7****4 8***3 9**2 10 *1 *///Core algorithm: var j=i;j<=10;j++//Idea: first analyze the results and observe the relationship between rows and columns. Then determine the algorithm of the inner loop // print an equilateral triangle, the same idea as above. var str=''; for (var i=1;i<=9;i++){ for (var j=1;j<=i;j++){ str+='*'; } str+='n'; } console.log(str);//To print the multiplication table, replace the asterisk of the equilateral triangle with the equation var str = ''; for (var i = 1; i <= 9; i++) { for (var j = 1; j <= i; j++) { /* str+='*'; */ str += i + '*' + i + '=' + i * j + ' t'; } str += 'n'; } console.log(str);//Remember: the outer loop loops once, and the inner loop is executed from beginning to end. It just prints the essence of the graphics.
Summary of for loops.
while loop
The while statement can execute a specified piece of code in a loop under the premise that the conditional expression is true, until the expression does not meet the condition, the loop ends
.The syntax structure of the while statement
while (conditional expression) {
//Loop body statement;
}
Execution idea:
first execute the conditional expression, if the condition is true, then execute the loop body code, otherwise, exit the loop and execute the following code
to execute the loop
body code. After the loop body code is executed, the program will Continue to judge and execute the conditional expression. If the condition is still true, continue to execute the loop body. The entire loop body process will not end until the loop condition is false.
The flow control chart is as follows
Code demonstration
var num=1; //Initialize variables while(num<=10){//Conditional expression console.log('Hello world'); num++;//Operation expression }
Note:
There is also an operation expression in while to complete the update of the counter and prevent an infinite loop (I did not add an operation expression, but when I ran the code, the Google Chrome interface was black).
There should also be counter initialization variables in it.
The while loop can be equivalent to the for loop to a certain extent. You only need to put the initialized variables, conditional expressions, and operation expressions in the while into the for loop.
Code demonstration
//Print a person's life, from 1 year old to 120 years old var age = 1; while (age <= 120) { console.log('This person is this year' + age + 'years old'); age++; } //2. Calculate the sum of all integers between 1 and 100 var sum = 0, i = 1; while (i <= 100) { sum += i; i++; } console.log(sum); //3. Open a dialog box, do you love me? If you enter I love you, it will prompt the end, otherwise it will keep asking var message='Do you love me'; while(message!=='I love you'){ message=prompt('Do you love me?'); } alert('I love you too');
do...while loop
do...while statement is actually a variant of while statement. This loop will first execute the code block once, and then judge the conditional expression. If the condition is true , the loop body will be executed repeatedly, otherwise it will exit the loop
do... The syntax structure of the while statement is as follows
do {
//Loop body code - Repeat the loop body code when the conditional expression is true
}
Execution idea:
execute the loop body code once
and then execute the conditional expression. If the result is true, continue to execute the loop body code. If it is false, then Exit the loop and continue executing the following code.
Note: execute the loop body statement first, and then judge. We will find that the do...while loop statement will execute the loop body at least once.
process control
Code demonstration
//Print a person's life, from 1 to 120 years old var age = 1; do { console.log('This person is this year' + age + 'years old'); age++; } while (age <= 120); //2. Calculate the sum of all integers between 1 and 100 var sum = 0, i = 1; do { sum += i; i++; } while (i <= 100) console.log(sum); //3. Open a dialog box, do you love me? If you enter I love you, it will prompt the end, otherwise it will keep asking var message = 'Do you love me'; do { message = prompt('Do you love me?'); } while (message !== 'I love you'); alert('I love you too');
Summary of Loops
:continue is The word is used to jump out of this loop immediately and continue the next loop (the code after continue in the body of this loop will be executed one less time).
For example: If you eat 5 buns and there are bugs in the third bun, throw away the third bun and continue eating the fourth and fifth buns.
Code demonstration
for (var i = 1; i <= 5; i++) { if (i == 3) { continue; } console.log('I ate the ' + i + 'th bun'); } Result: //I ate the 1st bun //I ate the 2nd bun //I ate the 4th bun //I ate the 5th bun
break keyword
The break keyword is used to jump out of the entire loop immediately (End of cycle)
For example: After eating five buns, I found a worm on the third one and lost my appetite.
Code example
for (var i = 1; i <= 5; i++) { if (i == 3) { break; } console.log('I ate the ' + i + 'th bun'); } Result; //I ate the 1st steamed bun //I ate the 2nd steamed bun
identifier naming convention
variables, the function name must be meaningful, the name of the variable is generally a noun, the name of the function is generallya single-line comment
specification
for (var i = 1; i <= 5; i++) { if (i == 3) { continue; //Please note that there is a space before the single line comment } console.log('I ate the ' + i + 'th bun'); }
Operator specification
//Reserve a space on the left and right sides of the operator for (var i = 1; i <= 5; i++) { if (i == 3) { break; } console.log('I ate the ' + i + 'th bun'); }