Note source: Hook Education – big front end employment Training camp
Content: Notes, thoughts and experiences in the process of learning
Flow control statement
Expressions, statements
expression
An expression can produce a value, which can be an operation, a function call, a literal, and the expression can be placed anywhere the value is needed
Expressions always execute a result before participating in other programs
statements
Can be understood as a behavior, a program may have more than one statement, generally with a semicolon to separate statements
- The statement can be thought of as a command to the computer to execute this code
- General statements end with a semicolon, except for special structures
Flow control statement
Through a certain JS structure, to control the loading of JS, skip a section of code or cycle to execute a section of code
- Conditional branch statement
- Looping statements
Conditional branch statement
Belongs to a process control statement
If statement
The most commonly used conditional branch statement, which determines a condition before deciding which branch to execute
Writing method:If (conditional expression) {struct 1} else {struct 2}
Construct 1 is executed if the result of conditional expression execution is true, otherwise, construct 2 is executed
- Conditional expression: Executes a code that forces a Boolean result (true or fales) to participate in the program
- Structure: {} contains one or more lines of statements, and contains all statements that need to be executed, otherwise none will be executed
// The user input the number of copies, output whether pass
var num = parseFloat(prompt('Please enter the score'.' '));
// Check whether the number of copies is greater than or equal to 60
if (num >= 60) {
// Pass the execution
alert('Congratulations, you've passed.');
} else {
// Fail to execute
alert('I'm sorry you didn't pass.')}Copy the code
Matters needing attention
- The if statement does not execute both branches
- If the if statement does not branch else, the following statement is executed if the if statement is true; otherwise, the if statement is skipped
- If the structure after the if is a single line statement, you can omit {}, but it is not recommended, which may cause errors
- The effect is the same: no matter which structure the if statement executes, the following code is executed
Multi-branch if statement
Multiple criteria can be set to execute different code
Writing method:If (conditional expression) {struct 1} else if (conditional expression 2) {struct 2} else if (conditional expression 3) {struct 3}....... The else ()
Interpretation: Condition 1 conforms to execute structure 1, otherwise it is determined whether it conforms to, if it conforms to execute corresponding structure, if it does not meet the execution of the last else
// The user input the number of copies, output whether pass
var num = parseFloat(prompt('Please enter the number of copies'.' '));
if (num >= 85) { // Determine the score is greater than or equal to 85
alert('good');
} else if(num >= 75) { // Determine whether the score is greater than or equal to 75 and less than 85
alert('good');
} else if(num >= 60) { // Check whether the score is greater than or equal to 60 and less than 75
alert('pass');
} else { // None of the above conditions are met
alert('Fail');
}
Copy the code
Matters needing attention
- There can be multiple else ifs but only one else at most. If none of the preceding conditions are met, the if statement is skipped
- Jump phenomenon: If one of the conditions is met, the structure is directly executed. After the execution is completed, the following if condition is skipped and the following statement is directly executed
If statements are nested
If statements can resemble the nested effect of HTML structures, in which one or more if statements can be added
If you want to execute child if statements only if the parent if statement satisfies the condition, you can simplify multi-branch IF statements
// Requirements: Input age and gender to determine whether you are eligible for retirement age
var xb = prompt('Please enter your gender');
var nl = parseInt(prompt('Please enter your age'));
if (xb === 'male') {
if (nl >= 60) {
alert('You are eligible for retirement age');
} else {
alert('You are not eligible for retirement age'); }}else if (xb === 'woman') {
if (nl >= 55) {
alert('You are eligible for retirement age');
} else {
alert('You are not eligible for retirement age'); }}Copy the code
Ternary expression
The ternary operator, which must have three operands, is a conditional branching statement
Writing method:Conditions? Structure 1: Structure 2
Construct 1 is executed if the output is true, construct 2 is executed otherwise
// A ternary expression
console.log(true ? 1 : 0); / / 1
Copy the code
Advantages:
- In the binary case, the ternary expression is simple
- A ternary expression must evaluate the result to participate in the program, which can be used to assign a binary result to a variable
You can use a ternary expression if it’s a simple binary case
A switch statement
Also called a switch statement, allows a program to evaluate an expression (which may not be a Boolean value) and attempt to match the expression’s value to a case tag. If the match is successful, the program executes the statement
// How to write
switch(expression) {case 值1: structure1;
break;
case 值2: structure3;
break; .default: structure n;break;
}
Copy the code
Reading:
- Switch: keyword to enter a switch statement
- Expression: will find a value, this value will be compared with the value of the following case, the comparison process must be congruent matching, otherwise matching failure, if and mo I case value matching success, will execute the case structure
- Case: The value to be matched must be followed by a space
- Structure: the statement to be executed after a case match is successful
- Break: Breaks the structure and jumps out of the switch statement, simulating the jumping phenomenon of the if statement
- Drfault: Similar to the else in an if statement, executed if none of the previous cases matched successfully
// Requirements: input horoscope, output horoscope
var xz = prompt('Please enter your star sign');
switch (xz) {
case 'Aries' :
alert('白羊座运势');
break;
case 'Taurus' :
alert('Taurus horoscope');
break;
case 'Gemini' :
alert('Gemini');
break;
case 'Pisces' :
alert('Pisces');
break;
case 'Cancer' :
alert('Cancer');
break;
case '狮子座' :
alert('Leo');
break;
case 'Virgo' :
alert('处女座运势');
break;
case 'Libra' :
alert('天秤座运势');
break;
case 'Scorpio' :
alert('Scorpio');
break;
case Sagittarius :
alert('Sagittarius');
break;
case 'Capricorn' :
alert('Capricorn');
break;
case 'Aquarius' :
alert('Aquarius');
break;
default :
alert('Did you make a typo? ')
break;
}
Copy the code
Matters needing attention
Default can be left out, like else
The break keyword must be written in every case suggestion to simulate jumping off a building. If not written, the structure will not jump out, and all subsequent case statements will continue to execute until a break is encountered or all code execution is completed
Switch is recommended for matching multiple values from a single variable
Use the do not write break special effect
// Demand: input month, output the number of days in the month
var yf = parseInt(prompt('Please enter month'));
switch (yf) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
alert('There are 31 days in the month')
break;
case 2:
alert('There are 28 or 29 days in the month.');
break
default:
alert('There are 28 or 20 days in the month.')}Copy the code
Conclusion:
- If statement: All judgment scenarios can be used, most commonly
- Ternary expressions: used to assign one of two conditions
- Switch: Used when an expression matches multiple values
Looping statements
Execute code over and over until a condition is met
The for loop
A pre-test loop statement that evaluates a condition before executing a piece of code. If the output is true, the condition is executed; otherwise, it is not executed and the loop is broken
// The writing method
for(1); (2); ④) {③} ⑤// This can only cover part of the usage of for. Not all for loops are like this
forCreate a loop variable; The maximum or minimum value of a variable; Step size) {loop body; }Copy the code
Implementation process
For loop execution: If the value is true, the entry condition is true. If the value is false, the entry condition is false. No further execution is required. Jump out of the loop and execute the following statement at position ⑤.
If it can be executed to ③, ③ is a structure must be executed, and then the statement at ④ is executed, and then the statement at ② is executed, and then the statement at ② is returned to check whether it is true or false. If it is true, continue to execute ③ and then…. Until position ② yields a false result, the loop ends and the execution ⑤ is interrupted
// Demand: output xiaoming's 100th birthday data
for (let index = 1; index <= 100; index++) {
console.log('Xiao Ming Today' + index + 'old');
}
console.log('Xiao Ming is 100 years old.');
Copy the code
Matters needing attention
- There must not be two semicolons in the parentheses
- The for loop {} does not need a semicolon
- If the ② position is not written, it is equivalent to no entry condition, the condition is always true, the loop is always executed, it is equivalent to entering an infinite loop, this situation must not be allowed to occur
- As above, if the conditions set by ② are unreasonable, there will also be an infinite loop, so pay attention to not appear an infinite loop
- ③ position is a loop structure, can be nested any statement (if, for, etc.), to execute will be executed, executed after the completion of position ④
- If multiple levels are nested, ensure that the names of new variables are not repeated. Otherwise, problems may occur
Nonrigid usage
var a = 1;
for (console.log('I don't even have to create variables here, but I can only do it once.'); a< 10; console.log('a++, I don't have to write it here, I'm going to execute it every time I execute the body of the loop. ')) {
console.log(a);
console.log('I could even put a++ inside the body of the loop, and I'm going to execute it every time I execute the body of the loop.')
a++;
}
Copy the code
So the for loop isn’t fixed, as long as it’s structured
A nested loop
for (let i = 1; i <= 4; i++) {
for (let j = 1; j <= 4; j++) {
console.log(i, j); }}Copy the code
The do while loop
Belongs to the post-test loop statement, which refers to the execution of a loop body before judging the condition. If the condition is true, the next loop will be carried out, otherwise the loop will jump out
// The writing method
do{loop body}while(conditional expression);Copy the code
Interpretation of the
- Do: Do what, each cycle body
- While: when… “, judge whether the conditions are met
var i = 0;
do {
console.log(i);
i++;
} while (i < 10);
Copy the code
Matters needing attention
- Loop variables are defined outside
- The process of adding variables is written inside the body of the loop
- If variables are written inside a structure, an infinite loop occurs
- The effect of adding variables at the end of a loop body is different from that at the beginning
- The do while loop also executes the body at least once, because it is postjudged
The while loop
Pretest loop statements that determine the condition before the loop and execute the loop body if the condition is true
// The writing method
while(expression) {loop body}Copy the code
Matters needing attention:
- Variables participate in the loop and need to be defined externally
- The variables add themselves to the body of the loop
var i = 0;
while (i < 10) {
console.log(i);
i++;
}
Copy the code
conclusion
You can use do while when you encounter a loop statement that must be executed once
Use for and while loops if you must test conditions first
Break statement
Stop the current for, do while, while loop immediately, depending on the position, you can control the execution
// Need: find a number from 1 to 30 that is not divisible by 5
var i = 1;
while (i <= 30) {
if (i % 5= = =0) {
console.log(i);
// Break the loop when the condition is met
break;
}
i++;
}
Copy the code
Matters needing attention
You can only stop the loop that you are in. If the loop is nested, you can only stop a layer. If you want to stop specifying a layer of the loop, you can use the way to name the loop
// Give the outer layer for a name
xh:for (let i = 0; i < 4; i++) {
for (let j = 0; j < 4; j++) {
console.log(i,j)
if (j >= 2) {
// Use break to break the loop with the specified name
breakxh; }}}Copy the code
The continue statement
Skip the next loop and start the next one immediately. Used when a loop is halfway through and you find that it has achieved its goal or is not what you want, you can use continue to end the loop immediately
You don’t jump out of the whole loop, you jump out of the next loop
// Requirement: find all numbers between 1 and 30 that are not multiples of 5 and print them
var i = 1;
while (i <= 30) {
if (i % 5= = =0) {
i++;
// Jump out of this loop and go straight to the next loop
continue;
}
// Not a multiple of 5
console.log(i);
i++;
}
Copy the code
Matters needing attention:
If you use Breajk alone, you can only break out of the loop once. If the loop is still wrapped around the outer loop, you can’t stop it
// Skip the outer loop when j is fully divisible by 2
xh: for (let i = 0; i < 4; i++) {
for (let j = 1; j < 4; j++) {
// Determine the condition
if (j % 2= = =0) {
// Stop the for loop and enter the next loop
continue xh;
}
console.log(i, j); }}Copy the code
Exhaustive thought
All the data within the range of all the required data are enumerated, and these data are screened according to some rules, which is called exhaustive method.
technology
- For loop: Use the for loop to list all the data
- If statement: Filter the data needed for judgment
// Select all divisor of 6
// Use for to print all possibilities
for (let i = 1; i <= 6; i++) {
//if determines whether the value satisfies the condition
if(6 % i === 0) {
console.log(i); }}Copy the code
// Requirements: the user enters a positive number, and the program outputs all divisor numbers
// Takes user input and converts it to an integer
var num = parseInt(prompt('Please enter a positive integer'));
/ / filter
// List all the numbers
for (let i = 1; i <= num; i++) {
//if determines whether the value satisfies the condition
if(num % i === 0) {
console.log(i); }}Copy the code
Accumulator and multiplicator
accumulator
Sometimes what we need may not be a certain data, but the sum of some data, we can find a way to add these data together to store, called accumulator
The essence is a variable
Case study:
// Requirement: sum of all numbers between 1 and 10
// Create an accumulator
var num = 0;
/ / cycle
for (let i = 1; i <= 10; i++) {
num += i;
}
// Output the cumulative num
console.log(num);
Copy the code
Matters needing attention
- Variables must be defined outside the loop, not inside the loop
- The initial value of the accumulator must be set. If it is not set, an error may occur. Generally, the initial value is 0
- The last time is the final value, so use is used after the loop
Multiplicative device
It’s like an accumulator, but instead of adding, it’s multiplying
case
// Demand: 1-10 cumulative product (10!)
// Create the multiplier
var num = 1;
/ / cycle
for (let i = 10; i >= 1; i--) {
num *= i;
}
// Output num after multiplicative
console.log(num);
Copy the code
Matters needing attention
- Variables must be defined outside the loop, not inside the loop
- The initial value of the accumulator must be set. Otherwise, an error may occur. Generally, the initial value is 1
- The last time is the final value, so use is used after the loop
Case study: Daffodil count
Requirement: The sum of each digit to the third power equals itself
// // problem 24: find the number of daffodils
for (let i = 1000; i <= 9999; i++) {
let gw = i % 10,
sw = parseInt(i / 10) % 10,
bw = parseInt(i / 10 / 10) % 10,
qw = parseInt(i / 1000);
if (Math.pow(gw, 4) + Math.pow(sw, 4) + Math.pow(bw, 4) + Math.pow(qw, 4) === i) {
console.log(i + 'Is the number of daffodils'); }}Copy the code