[JavaScript in front-end tutorials] 04_JavaScript process control statement

Posted by bawla on Mon, 13 Dec 2021 08:19:57 +0100

JavaScript from getting started to mastering video through train:

        [1-200] JavaScript video tutorial, from introduction to mastery, with more cases of practice, easy to understand!

        [201-300] JavaScript video tutorial, from introduction to mastery, with more cases of practice, easy to understand!

JavaScript process control statement

Definition of statement

In ECMAScript, all code is composed of statements.

A line of code is a simple statement. In form, it can be a single line statement or a compound statement surrounded by a pair of braces "{}". The compound statement contains several simple statements, which can be treated as a single line statement. Compound statements are also called statement blocks.

Single line statement: a simple statement with one line of code

Compound statement: several simple statements enclosed by a pair of braces "{}", also known as statement blocks

Process control statement classification

Any complex program logic can be realized through three basic program structures: sequence, condition (Branch) and loop.

Sequential program structure is to execute statements sequentially from top to bottom; By default, the program is executed from top to bottom

Conditional (Branch) program structure is to execute different statements according to different situations;

The circular program structure is that some statements need to be executed repeatedly.

Conditional statement (branch statement)

if single branch statement

If else double branch statement

if - else if multi branch statement

Switch switch statement

Circular statement

for loop statement

while loop statement

Do while loop statement

For / in loop statement (enhanced for loop, foreach loop)

Conditional statement

The if statement is a conditional judgment statement, which has three formats:

Single branch conditional statements;

Double branch conditional statement

Multi branch conditional statement.

Conditional statements are used to perform different actions based on different conditions.

Single branch conditional statement

if() {} statement - use this statement to execute code only when the specified condition is true

if (/* Conditional expression */) {
  // Execute statement
}

Note:

(1) the return value in parentheses after if is a boolean expression or boolean value, that is, the return value of this expression can only be true or false.

(2) if the value of the expression is true, the statement is executed; if the value of the expression is false, nothing is executed.

         (3) A statement block enclosed in curly braces can have only one line of statement or multiple lines of code. A statement block is usually executed as a whole. If the statement block has only one line of statement, the curly braces can be omitted, because the single line statement itself is a whole and there is no need to define them as a whole. It is recommended to add curly braces;

Double branch conditional statement

         if()...else statement - executes statement 1 when the condition is true and statement 2 when the condition is false

if (/* Conditional expression */){
  // Set up execution statement
} else {
  // Otherwise, execute the statement
}

if (Conditional expression){
    Statement 1;
}else {
    Statement 2;
}

Note:

(1) the return value in parentheses after if is a boolean expression or boolean value, that is, the return value of this expression can only be true or false.

(2) if the value of the if expression is true, execute statement 1; if the value of the expression is false, execute statement 2.

Multi branch if conditional statement

         if()...else if()....else statement - use this statement to select one of multiple code blocks for execution

if (/* Condition 1 */){
  // Set up execution statement
} else if (/* Condition 2 */){
  // Set up execution statement
} else if (/* Condition 3 */){
  // Set up execution statement
} else {
  // Last default execution statement
}

Syntax:

if (Conditional expression) {
    Statement 1;
} else if (Conditional expression) {
   Statement 2;
} ...
else{
   sentence n;
}

Note: the expression in the if statement () is automatically converted to a Boolean value.

If the condition is met, the corresponding statement is executed, and then the statement ends; If none is satisfied, execute else statement block; Of course, else statement blocks may not exist.

switch multi conditional selection statement

Switch statement, also known as switch statement, is similar to multiple if statements. The former is used for equivalence judgment, and the latter is used for interval value and equivalence judgment. The function of the switch statement is to jump to different statements according to the value of the expression. Switch statements are used to perform different actions based on different conditions.

Syntax:

switch (expression) {
  case Constant 1:
    sentence;
    break;
  case Constant 2:
    sentence;
    break;
  case Constant 3:
    sentence;
    break;
  ...
  case constant n:
    sentence;
    break;
  default:
    sentence;
    break;
}

switch multi conditional selection statement:

First set the expression, and then the value of the expression will be compared with the constant expression of each case in the structure. If there is a match, the code block associated with the case is executed.

Use break to prevent code from automatically running to the next case. Default keyword to specify what to do when the match does not exist, that is, when there is no matching value, execute the statement under default.

The switch statement uses a congruent operator when comparing values, so no type conversion occurs (for example, the string '10' is not equal to the value 10)

Working principle:

First set the expression n (usually a variable).

The value of the expression is then compared with the value of each case in the structure.

If there is a match, the code block associated with the case is executed.

Use break to prevent the code from automatically running to the next case.

default keyword to specify what to do when the match does not exist; It's equivalent to else in if

Note: 1. Generally, the break statement under each case statement cannot be omitted. The break statement means to exit the switch statement. If omitted, the code in the next case statement will continue to be executed until the break statement jumps out of the switch statement. 2. The default statement can appear anywhere in the switch statement. If it is placed at the end, the break statement can be omitted. The default statement can also be omitted. 3. There is no order for each case statement, but it is recommended to follow the order of the value of the constant expression from small to large. 4. The switch statement is used for equivalence judgment, that is, the result of the expression is a specific value; The value of the expression of multiple if selection results is an interval, such as greater than 100 and less than 200.

Enter a number and print the corresponding week

var day = 10;
switch (day) {
    case 1:
        console.log('Monday');
        break;
    case 2:
        console.log('Tuesday');
        break;
    case 3:
        console.log('Wednesday');
        break;
    case 4:
        console.log('Thursday');
        break;
    case 5:
        console.log('Friday');
        break;
    case 6:
        console.log('Saturday');
        break;
    case 7:
        console.log('Sunday');
        break;
    default:
        console.log('The value entered is not in the week range');
        break;
}

Conditional statement exercise

Case:

Find the maximum number of two numbers

var num1 = 2;
var num2 = 5;

if (num1 > num2) {
    console.log('The maximum value is:' + num1);
} else {
    console.log('The maximum is: ' + num2);
}

Judge whether a number is even or odd

// Judge whether a number is even or odd
var num = 5;
if (num % 2 === 0) {
    console.log('num It's an even number');
} else {
    console.log('num It's an odd number');
}

Score conversion, converting the percentage system to ABCDE < 60 e 60-70 D 70-80 C 80-90 B 90 - 100 a

// Score conversion, converting the percentage system to ABCDE < 60 e 60-70 D 70-80 C 80-90 B 90 - 100 a
var score = 59;
if (score >= 90 && score <= 100) {
    console.log('A');
} else if (score >= 80 && score < 90) {
    console.log('B');
} else if (score >= 70 && score < 80) {
    console.log('C');
} else if (score >= 60 && score < 70) {
    console.log('D');
} else {
    console.log('E');
}

var score = 59;
if (score >= 90) {
    console.log('A');
} else if (score >= 80) {
    console.log('B');
} else if (score >= 70) {
    console.log('C');
} else if (score >= 60) {
    console.log('D');
} else {
    console.log('E');
}

var score = 6; 
score = parseInt(score / 10);
switch (score) {
    case 10:
    case 9:
        console.log('A');
        break;
    case 8:
        console.log('B');
        break;
    case 7:
        console.log('C');
        break;
    case 6:
        console.log('D');
        break;
    default: 
        console.log('E');
        break;
}

Loop program structure

If you want to run the same code over and over again, it's convenient to use loops. For example, output "I love HTML5 programming" 100 times on the page. If you don't need a loop, document Write ("I love HTML5 programming < br / >"); Write it 100 times. If a loop is used, the code can be written as follows:

for(var i=1;i<=100;i++){
	document.write("I love HTML5 programming<br/>");
}

The structure of the loop program has three elements: the initial value of the loop, the loop condition (the end value of the loop) and the iteration of the loop. The so-called iteration of the loop is how to go from the initial value to the end value, such as adding 1 or 2 each time, and so on. Of course, a loop program also contains a loop body.

while statement

The while loop executes the code block when the specified condition is true. It is a loop statement that judges first and then runs. That is, the loop body can be run only after the condition is met. Used when the number of cycles is uncertain.

Syntax:

// When the loop condition is true, execute the loop body,
// When the loop condition is false, the loop ends.
while (Cycle condition) {
  //Circulatory body
}

Code example:

// Print all numbers between 1-100
var i = 1;
while (i <= 100) {
    console.log(i);
    // i = i + 1;
    // i += 1;
    i++;
}

// Calculate the sum of all numbers between 1 and 100
// initialize variable
var i = 1;
var sum = 0;
// Judgment conditions
while (i <= 100) {
  // Circulatory body
  sum += i;
  // Self increasing
  i++;
}
console.log(sum);

Case:

Print multiples of 7 within 100

// Print multiples of 7 within 100
var i = 1;
while (i <= 100) {
    // Judge whether the current i is a multiple of 7
    if (i % 7 === 0) {
        console.log(i);
    }
    // i self + 1
    i++;
}

Print all even numbers within 100

// Print all even numbers within 100
var i = 1;
while (i <= 100) {
    // Determine whether the current i is even
    if (i % 2 === 0) {
        console.log(i);
    }
    // i self + 1
    i++;
}

Print the sum of all even numbers within 100

// Print the sum of all even numbers within 100
var i = 1;
var sum = 0;
while (i <= 100) {
    // Judge whether the current i is an even number. If it is an even number, it will be accumulated
    if (i % 2 === 0) {
        sum += i;
    }
    // i self + 1
    i++;
}
console.log(sum);

Case 1: cyclic output of values starting from 1; The cycle does not end until this value (n*2+8)/3 is 20

Case 2: input the string from the pop-up box until the input value is end

var inputStr = prompt("Please enter a string"); 

do...while Loop

         do... The while loop is a variant of the while loop. Before checking whether the condition is true, the loop will execute the code block under do (loop body) at least once, and then repeat the loop if the condition is true, otherwise exit the loop body. It is often used to execute the loop body at least once and then judge whether to continue the loop.

Syntax:

do {
  // Circulatory body;
} while (Cycle condition);

Code example:

// initialize variable
var i = 1;
var sum = 0;
do {
  sum += i;//Circulatory body
  i++;//Self increasing
} while (i <= 100);//Cycle condition

Case:

// Find the sum of all multiples of 3 within 100
var i = 1;
var sum = 0;
do {
    // Circulatory body
    // Judge whether it is a multiple of 3. If it is a multiple of 3, it is accumulated
    if (i % 3 === 0) {
        sum += i;
    }
    // i self + 1
    i++;
} while (i <= 100);
console.log(sum);

for statement

while and do while is generally used to solve the cycle of unacknowledged times. The for loop is generally convenient when the number of cycles is determined.

Syntax:

// The expressions of the for loop are; It's separated by numbers. Don't write it,
for (Initialization expression 1; Judgment expression 2; Self increasing expression 3) {
  // Circulating body 4
}

Statement 1: execute before the start of the loop body (code block), that is, the initial value of the loop.

Statement 2: define the conditions for running the loop (code block). If statement 2 returns true, the loop will start again. If false is returned, the loop will end

Statement 3: after the loop (code block) has been executed, it is the iterative part of the loop. Statement 3 has many uses. The increment can be negative (i --) or greater (i=i+15)

for loop execution mechanism:

Execution sequence: 1243 -- 243 -- 243 (until the cycle condition becomes false)

  1. Initialization expression

  2. Judgment expression

  3. Self increasing expression

  4. Circulatory body

for...in statement

        for... The in statement is used to traverse the attributes of an array or object (usually, we use the for/in statement to cycle through the attributes of an object, and all elements in the array can be traversed in the array).

        for... Each time the code in the in loop is executed, it will operate on the elements of the array or the attributes of the object.

for..in traversal array

// Define an array
var arr = [13,21,34,42,53,63];

// Ordinary for loop traversal
for(var i = 0;i < arr.length;i++){
    console.log(arr[i]);
}

// Use for In traversal array
for(var i in arr){
    console.log(arr[i]);
}

for..in traversal object

// Create an object
var person = {
    name : "jack",
    age : 12,
    height: 178
}

//Enumerate object property names and their values
for(var pro in person){
    console.log(pro+" "+person[pro])
}

In the JavaScript language, nesting of loop statements is supported, that is, nesting another loop statement in one loop statement, that is, for loop statements can nest for statements, while loop statements, or do The while loop statement is the same as other loop statements.

It should be noted that break and continue statements are used in loop nesting. These two statements are only valid for the nearest loop statement. For example, if the break statement is used in an inner loop statement, only the inner loop will be exited, and the outer loop will not be affected.

Circular sentence practice

Print 1-100 All numbers between
for (var i = 1; i <= 100; i++) {
    console.log(i);
}

var i = 1;
for (; i <= 100; ) {
	console.log(i);
	i++;
}

Seek 1-100 Sum of all numbers between
var sum = 0;
for (var i = 1; i <= 100; i++) {
    // sum = sum + i;
    sum += i;
}
console.log(sum);

Seek 1-100 Average of all numbers between
var sum = 0;
var avg;
for (var i = 1; i <= 100; i++) {
    sum += i;
}
avg = sum / 100;
console.log(avg);

Seek 1-100 The sum of all even numbers between
var sum = 0;
for (var i = 1; i <= 100; i++) {
    // Even number found
    if (i % 2 === 0) {
        sum += i;
    }
}
console.log(sum);

Find 1 at the same time-100 The sum of all even and odd numbers
var oddSum = 0; // Odd sum
var evenSum = 0; // Even sum
for (var i = 1; i <= 100; i++) {
    // Judge whether i is odd or even
    if (i % 2 === 0) {
        // even numbers
        evenSum += i;
    } else {
        //Odd number
        oddSum += i;
    }
}
console.log('Odd sum:' + oddSum);
console.log('Even sum:' + evenSum);

Print square
// Reasons for using string spelling
// console.log output duplicate content
// console. There is a newline after the introduction of the default output content of log
var start = '';
for (var i = 0; i < 10; i++) {
  for (var j = 0; j < 10; j++) {
    start += '* ';
  }
  start += '\n';
}
console.log(start);

Print right triangle
var start = '';
for (var i = 0; i < 10; i++) {
  for (var j = i; j < 10; j++) {
    start += '* ';
  }
  start += '\n';
}
console.log(start);

Print 9*9 multiplication table
var str = '';
for (var i = 1; i <= 9; i++) {
  for (var j = i; j <=9; j++) {
    str += i + ' * ' + j + ' = ' + i * j + '\t';
  }
  str += '\n';
}
console.log(str);

Jump statement

break: immediately jump out of the whole loop, that is, at the end of the loop, start executing the contents after the loop (directly jump to braces)

Continue: immediately jump out of the current loop and continue the next loop (jump to the place of i + +)

The continue statement can only be used in a loop; break can be used in loops or switch es.

Case:

Find integer 1~100 If it is required to encounter a number with bit 3, the accumulation will be stopped
 Find integer 1~100 The cumulative value of, but it is required to skip all numbers with bit 3
var sum = 0;
for (var i = 1; i <= 100; i++) {
    if (i % 10 === 3) {
        // If a number with bit 3 is found, proceed to the next cycle
        continue;
    }
    sum += i;
}
console.log(sum);

debugging

  • How JavaScript was debugged in the past

    • alert()

    • console.log()

  • breakpoint debugging

Breakpoint debugging refers to setting a breakpoint on a certain line of the program. When debugging, the program will stop running 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.

  • Commissioning steps

Press in the browser F12-->sources-->Find the file to debug-->Set a breakpoint on a line of the program
  • Relevant operations during commissioning

Watch: Monitoring, through watch It can monitor the change of variable value, which is very common.
F10: The program is executed step by step. Let the program execute line by line. At this time, observe watch The change in the value of the variable in.
F8: Skip to the next breakpoint. If there is no breakpoint, the program execution ends.

tips: monitor variables. Do not monitor expressions. If expressions are monitored, the expressions will also be executed.

  1. The ability of code debugging is very important. Only when you learn code debugging can you learn your ability to solve bugs. Beginners should not stop debugging if they find it troublesome to debug the code. They will certainly learn it if they spend some time on knowledge, but they will never learn it if they don't practice it.

  2. Today's code debugging is very simple. Students are only required to remember the functions of these buttons for code debugging. They will learn a lot of code debugging skills later.

Code specification

1.Naming conventions	
	The naming of variables and functions must be meaningful
	Variable names are generally nouns
	The names of functions are usually verbs
2.Variable specification   
	There should be spaces before and after operators
	var name = 'zhangsan';	  5 + 6
3.Annotation specification
	// Here are the notes
4.Space specification
	if (true) {
      
	}
	for (var i = 0; i <= 100; i++) {
      
	}
5.Line feed specification
	var arr = [1, 2, 3, 4];
	if (a > b) {
      
	}
	for (var i = 0; i < 10; i++) {
      
	}
	function fn() {
      
	}

Topics: Javascript Front-end ECMAScript