preface
Obviously, the sequence of program execution has a significant impact on the running results of the program, so the process control statement was born. It has three basic structures: sequence structure, selection structure and loop structure.
- Sequential structure: code is executed from top to bottom.
- Select structure: perform different operations according to different conditions.
- Loop structure: repeat the same operation under loop conditions.
Branch statement
IF branch statement
- Single branch statement
if(Judgment conditions){ Execute statement; //(executed when the condition is true) }
- Double branch statement
if(Judgment conditions){ Execute statement; //Execute when the judgment condition is true }else{ Execute statement; //Execute when the judgment condition is false }
- Multi branch statement
if(Judgment condition 1){ Execute statement 1; }else if(Judgment condition 2){ Execute statement 2; } ... else{ Execute statement;(If none of the above conditions is true, execute this statement.) }
- Any expression can be written in If(), and the data type will be automatically converted to Boolean value.
- Classic cases of branch statements:
<script> // Judge whether a number is odd or even? var num = 9; if(num % 2 == 0){ alert(num + "It's an even number!"); }else{ alert(num + "It's an odd number!"); } // Find the maximum number of two numbers? var num1 = 10, num2 = 20; if(num1 > num2){ alert("The maximum number is:" + num1); }else{ alert("The maximum number is:" + num2); } // Judge whether a year is a leap year or a normal year? (leap years can be divided by 4 and not by 100, or by 400) var year = 2020; if(year % 4 == 0 && year % 100 != 0 || year % 400 == 0){ alert("This is a leap year:" + year); }else{ alert("This is a normal year:" + year); } </script>
SWITCH branch statement
Execution process: calculate the value of the Switch() statement expression, and then match it with the value after Case. If it is equal, the match is successful, and execute the execution statement under the corresponding Case option.
switch(expression){ case Constant 1: Execute statement 1; break; case Constant 2: Execute statement 2; break; ... default: Execute statement; //This statement is executed when all case options fail to match. break; }
Note: generally, do not omit break and default. Break represents the termination of the current switch statement, and default can help us complete error checking and fault tolerance.
Note: to match the determined results, switch statements are preferred. IF judgment is required, only IF statements can be used.
[note] if multiple Case execution statements are the same, they can be put together, omit Break, and make use of the penetration principle of Case.
//For example, enter the month to display the days of the month. Use case penetration to omit break and simplify the code: var month = 4; var year = 2000; switch(month){ case 1: case 3: case 5: case 7: case 8: case 10: case 12: alert("31 day"); break; case 2: if(year % 4 == 0 && year % 100 != 0 || year % 400 == 0){ alert("29 day"); }else{ alert("28 day"); } break; default: alert("30 day"); break; }
Double branch ternary operator
- Syntax: expression 1? Expression 2: expression 3;
- Execution order: first judge whether expression 1 is true or false, execute expression 2 if it is true, and execute expression 3 if it is false.
<script> // To judge the parity of numbers, write the ternary operator: var num = 9; num % 2 == 0 ? alert("This is an even number") : alert("This is an odd number"); </script>
Circular statement
- Classification of cycles:
- while Loop
- do_while Loop
- for loop
- Benefits of using recycling:
- The code is concise without redundancy.
- It is convenient for later maintenance.
- To define a cycle
- Determine the number of cycles.
- Determine the conditions of the cycle.
- Determines the execution statement of the loop.
- You can't let the loop condition hold forever, which will cause an endless loop and cause the page to get stuck.
- Loop conditions can write any expression, and the data type is automatically converted to Boolean.
- Two keywords in the loop
- break to terminate the current loop.
- continue, skip this cycle and directly enter the next cycle.
- About the number used for counting in a loop
It is usually called index and named i. other subscripts in the inner layer of the nested relationship can be selected in the order of i j k l m n (programming habit).
WHILE loop
- Execution rule: execute the loop statement when the loop condition is established until the loop condition is not established.
while(Cycle condition){ Circular statement; }
- WHILE cycle foundation case:
<script> //Find the sum of 1 ~ 100 var i = 1; var sum = 0; while(i <= 100){ sum += i; i++; } alert(sum); //Find 1 - 1 / 2 + 1 / 3 - 1 / 4- Sum of 1 / 100 var i = 1; var sum = 0; while(i <= 100){ if(i % 2 == 0){ sum -= 1 / i; }else{ sum += 1 / i; } i++; } alert(sum); //Print out all leap years in 1000-2000 and output them in the form of four numbers per line var i = 1000; var num = 0; while(i <= 2000){ if(i % 4 == 0 && i % 100 != 0 || i % 400 == 0){ document.write(i + " "); num++; if(num % 4 ==0){ document.write("<br/>"); } } i++; } </script>
Do... WHILE loop
Execution rule: run the loop statement once, and then judge whether the loop condition is true. The loop statement will be executed at least once.
do{ Circular statement; }while(Cycle condition);
FOR cycle
Execution rules:
- Execute expression 1 first (yes and only once)
- Then execute expression 2 to judge whether the loop conditions are met. If true, execute the loop statement. If false, end the loop.
- If expression 2 is true, after executing the loop statement, execute expression 3, and then return to expression 2 to judge whether the loop condition is true.
for(Expression 1; Expression 2; Expression 3){ Circular statement; } for(Define cycle initial value; Cycle condition; Accumulation condition){ Circular statement; }
Dead cycle
The cycle condition is always established to form a dead cycle.
Common dead cycles:
<script> //while loop, which is commonly used. while(1){ } //do...while loop. do{ }while(1); //for loop. for(;;){ } </script>
Circular exercises
<script> //Print triangles for(var i = 1; i <= 5; i++){ for(var j = 1; j <= i; j++){ document.write("π"); //For the first loop, i=1, J < = 1, the inner loop condition is established once, and the loop statement is executed once, that is, an expression is output //For the second loop, i=2, J < = 2, the inner loop condition is established twice, and the loop statement is executed twice, that is, two expressions are output //For the fifth cycle, i=5, J < = 5, the inner cycle condition is established for 5 times, and the cycle statement is executed for 5 times, that is, five expressions are output } document.write("<br/>"); } //Print 99 multiplication table for(var i = 1; i <= 9; i++){ for(var j = 1; j <= i; j++){ document.write(i + "*" + j + "=" + (i*j) + " " ) } document.write("<br/>"); } //Print inverted triangle for(var i = 1; i <= 5; i++){ for(var k = 1; k <= 5 - i; k++){ //First output 5-i spaces, and then output expressions document.write("π"); } for(var j =1; j <= i; j++){ document.write("π"); } document.write("<br/>"); } //There is a tank on the mountain that can hold 50 liters of water. Now there are 15 liters of water. The old monk asked the little monk to carry water down the mountain. He can carry 5 liters each time. How many times does the little monk have to carry water before he can fill the water tank? var water = 15; var count = 0; //Define a count variable while(water < 50){ water += 5; count++; } alert("Little monk, you have to choose" + count + "Only once can the water tank be filled with water!"); //Judge whether a number is a prime number (which can only be divided by 1 and itself) or a composite number (which can be divided by other numbers except 1 and itself). Start from 2. var num = 11; var isYes = false; //Let's assume that num can only be divided by 1 and itself, that is, prime for(var i = 2; i < num ; i++){ if(num % i == 0){ isYes = true; //Use the value of i to take the value of remainder 2~num-1. If the remainder is 0, it will overturn the previous hypothesis and prove that num is a composite number break; //Jump out of current loop } } if(isYes){ alert(num + ",This is a composite number") }else{ alert(num + ",This is a prime number"); } //The king rewarded the master who invented chess. The master said he wanted wheat. There were 64 squares in chess. The first one put a grain of wheat, and the back one put twice as much as the front one. When the chessboard is full, you need so much wheat. Ask for the number of wheat? var num = 1; var sum = 0; for(var i = 1; i <= 64; i++){ sum += num; num *= 2; } alert(sum); //Find the number of daffodils. The number of daffodils is a three digit number, and the sum of the cubes of hundreds and tens is equal to the number itself. for(i = 100; i < 1000; i++){ var a = i % 10; var b = parseInt(i / 10) % 10; var c = parseInt(i / 100); var sum = Math.pow(a,3) + Math.pow(b,3) + Math.pow(c,3); //Math.pow(x,y) finds the Y power of X. if(i == sum){ document.write(i + "<br/>"); } } //Find the maximum common divisor of two numbers (hint: judge from the smaller number, and continuously reduce it to 1). var num1 = 20; var num2 = 16; var min = num1 > num2 ? num2 : num1; while(1){ if(num1 % min == 0 && num2 % min == 0){ break; } min--; } alert(num1 + "and" + num2 + "The greatest common divisor of is" + min); //Find the least common multiple of the two numbers. The maximum value is the product of the two numbers, and the minimum value is the maximum number of the two numbers. First take out the maximum number of the two numbers, and then judge in turn until the product of the two numbers. var num1 = 3; var num2 = 4; var max = num1 > num2 ? num1 : num2; while(1){ if(max % num1 == 0 && max % num2 == 0){ break; } max++; } alert(num1 + "and" + num2 + "The least common multiple of is:" + max); //In the five digits, the symmetrical number is called palindrome number. Find all palindromes, such as 12321. var count = 0; //Define the variable count for counting for(var i = 10000; i < 100000; i++){ var a = i % 10; //Extract single digits var b = parseInt(i / 10) % 10; //Extract ten digits var c = parseInt(i / 1000) % 10; //Extract thousands var d = parseInt(i / 10000); //Extract ten thousand digits if(a == d && b == c){ document.write(i + " "); count++; if(count % 20 == 0){ document.write("πLet me see how many more?" + "<br/>"); } } } // Enter a specific date to calculate the day and week of the current year? (January, March, may, July, August, October and December are 31 days. February in leap year has 29 days; February in normal year has 28 days.) var year = 2021; var month = 7; var date = 25; var sum = 0; switch(month){ case 12: sum += 30; case 11: sum += 31; case 10: sum += 30; case 9: sum += 31; case 8: sum += 31; case 7: sum += 30; case 6: sum += 31; case 5: sum += 30; case 4: sum += 31; case 3: sum += 28; if(year % 4 == 0 && year % 100 != 0 || year % 400 == 0){ sum += 1; } case 2: sum += 31; case 1: sum += date; break; default: alert("error"); break; } var week = Math.ceil(sum / 7); // Math.ceil(); Round up alert(year + "year" + month + "month" + date + "Day is" + year + "The second day of the year" + sum + "Day, day" + week + "Zhou," + "Today is better than yesterday. This is the so-called hope. Please continue to refuel!" ) </script>