preface

You will learn about this in this article

  • Sequence of statements
  • Branch statements
  • If judgment,switch,while cycle bad,do.. While loops,for loops, true and false in expressions

In the program code, we often use the flow control statement, which is used to control the execution sequence of each statement in the program. The combination of statements can complete a small logical module with certain functions

The flow control mode adopts three basic flow structures stipulated in structured programming, namely, sequence structure, branch structure and cycle structure, as shown in the figure below:

Sequence of statements

Execute from top to bottom in the normal statement order

Branch statements

Select execution based on certain conditions

  • If statement (used for a single condition)
  • If-else statements (used for both cases)
  • If-else -if statement (multiple if nested)
  • While statement (usually as soon as we enter, we need to judge, we need to execute a set of statements when the condition is true)
  • Switch statement (multiple case clause matches)

If statement

A conditional statement is a code structure that tests the truth of an expression and executes different code based on the result of a Boolean expression. That is, a conditional statement allows a program to choose which program statements to execute

writing

If (conditional expression) {statement body; }Copy the code

Points to note:

  • The result of a conditional expression must be of Boolean type
  • The statement body can contain one or more statements. If the statement body contains only one statement, {} can be omitted
  • You can use the ternary operator instead

Application scenarios

The single if statement is recommended for determining ranges or ranges when the condition is single

Programming problem

Maximize: Write a method to find the largest of two numbers A and b

Example: Input: A = 1, b = 2 Output: 2Copy the code

Method 1: If… else.

var maximum = function(a, b) { if(a-b>0) { return a; }else { return b; } // or as follows: trim operator return a-b>0? a:b; } maximum (1, 2)Copy the code

Method 2: Use the data function Max provided by Math

Var maximum = function(a, b) {return math.max (a,b)} maximum(1,2)Copy the code

In actual program code: the use of if is ubiquitous

For example, in the example above: the button on the right is enabled if the form input field is not empty, otherwise disabled

If (newstate.inputVal! ="") { newState.btnDisable = false; <button onClick = {hanldeAddContent} disabled = {btnDisable}> Submit </button>Copy the code

Compared with the if.. Else statements,switch statements may be less proficient,switch statements only support branching of constant values, while if statements support more flexible, arbitrary Boolean expressions but are generally more efficient than a series of nested if statements; The logic is clearer

A switch statement

Matches the value of the expression with the case clause and executes the statement associated with that case

Application scenario: This parameter is used for equivalence judgment

Writing:

Switch (Express expression) {case value1: // If the result of express matches that of Value1, execute the statement body 1; break; Case value2: // Execute body 2 of the express statement if the result matches value2. break; . Case valueN: // If the express result matches valueN, execute the statement body 3. break; Default: // If express does not match any of the above values, execute the statement body 4. break; }Copy the code

Matters needing attention:

  • One of the main differences between the switch statement in JS and other languages is that the judgment expression in the switch statement can be of any type, whereas other languages, such as Java, require the expression to be an integer
  • An expression can be a variable, a constant, or a complex expression using the congruent === symbol. Express is an expression used to match case substatements
  • A case clause must be a constant expression. There can be more than one case clause, but the value of each case clause cannot be repeated
  • The default clause is similar to the else statement in an if statement. It can be omitted, but is not recommended. It is generally used to deal with other cases
  • The break clause indicates the exit of the switch statement body, and the break statement can also be omitted. Once omitted,break penetration phenomenon will occur, and the break clause is generally not omitted

Example: when dialing 10086, press 1 for business inquiry, 2 for mobile phone recharge, 3 for business handling, 4 for password service and stop and answer machine, 8 for group service, 0 for manual service

For example, if in Redux is Redux as switch statement

The if statement looks like this

import * as constants from "./actionTypes"; function reducer(state = defaultStatus, action) { if(action.type === constants.HANDLE_INPUT_CHANGE) { const newState = JSON.parse(JSON.stringify(state)); if(newState.inputVal ! ="") { newState.btnDisable = false; } newState.inputVal = action.value; return newState; } if(action.type === constants.HANDLE_ADD_CONTENT) { const newState = JSON.parse(JSON.stringify(state)); newState.list.push(state.inputVal); newState.inputVal = ""; newState.btnDisable = true; return newState; } if(action.type === constants.HANDLE_DELETE_ITEM) { const newState = JSON.parse(JSON.stringify(state)); newState.list.splice(action.index, 1); return newState; } return state; }Copy the code

After being overwritten by the switch, it looks as follows

import * as constants  from "./actionTypes";

function reducer(state = defaultStatus, action) {
    const newState =  JSON.parse(JSON.stringify(state));
    switch(action.type) {
        case constants.HANDLE_INPUT_CHANGE:
                if(newState.inputVal !="") {
                    newState.btnDisable = false;
                }
                newState.inputVal = action.value;
                return newState;
        case constants.HANDLE_ADD_CONTENT:
                newState.list.push(state.inputVal);
                newState.inputVal = "";
                newState.btnDisable = true;
                return newState;
        case  constants.HANDLE_DELETE_ITEM:
                newState.list.splice(action.index, 1);
                return newState;
        default:
             return state;     
    }

}
Copy the code

The switch statement has several characteristics compared to the if statement

  • The switch statement is often used to determine fixed values
  • Anything you can do with switch, you can do with IF, you can’t do with DSLR
  • In actual development, if code optimization is needed, switch statements can be used instead when multiple conditions are judged to be equivalent conditions

Summary: Select the use of control statements

  • If statement: for a situation
  • If-else statements: Black or white for both cases
  • Multiple IF statements: Used for interval determination in multiple cases
  • Nested if statements: for multiple conditions (switch can be used instead for equivalence judgment)
  • Swtich statement: for the condition is equivalent, a fixed value of the case above said the selection structure, next to the loop structure

The while loop

You can loop through a specified piece of code if a conditional expression is true, and end the loop if the expression is not true

Application scenario: If you want to execute a set of statements when the condition is true at first, and you don’t know how many times the loop is executed, only that the loop continues when a certain condition is reached, use a while loop

writing

While statement (conditional expressionCopy the code

Conditional expression:

Is evaluated before each loop. If the evaluation is true, the statement will be executed. If the evaluation is false, the next statement is executed out of the while loop

statement:

The statement is executed as long as the conditional expression is evaluated to true. To execute multiple statements in a loop, use block statements ({… }) wrap multiple statements

Note: Use the break statement to stop the loop until the conditional expression evaluates to true

Find the sum of 1-100

var number = 1; Var sum = 0; var sum = 0; Function getSum(n){while(number<n) {sum += number; ++number; } return sum; } getSum(100);Copy the code

A few things to note when using the while loop:

  • The initial conditions for the loop are defined outside
  • The body of the while is executed only if the conditional expression is true
  • The while loop should have updates to loop variables, otherwise it will cause an infinite loop

do… The while loop

Creates a loop that executes the specified statement until the conditional expression value is false. The conditional expression is tested after the statement is executed, so the specified statement is executed at least once

Writing:

Do {statement body; }while(conditional expression loop condition)Copy the code

Usage scenario: Often need to be implemented at the beginning, just like many games, at the beginning, let you play a game first, through how many levels, before proceeding to the next link.

The difference with while is that:

  • Whle loops are judge before execute, while do.. While is execute first, judge later

  • When the first condition fails, the while is not executed, while the do-while is executed at least once regardless of whether the condition is true

  • An expression evaluated each time in the loop. If the conditional expression loop condition is true, the statement executes again. When the conditional expression loop condition is false, jump to do… The statement after while

For example, change the while statement to do.. While writing

var number = 1;
var sum = 0;
function getSum(n) {
    do {
          sum += number;
          ++number;
    } while (number < n);

    return sum;
}

console.log(getSum(3));
Copy the code

The for loop

Used to create a loop that contains three optional expressions surrounded by parentheses, separated by semicolons, followed by a statement to execute within the loop

Application scenario: This mode is used when the number of cycles is fixed

Writing:

For (initialize a variable; Cyclic conditions; Loop increment){loop body; }Copy the code

Matters needing attention:

  • All three expressions in the parentheses in the for header are optional

  • Initialization values can be defined inside parentheses, they can be defined outside, but I strongly recommend that you define them inside. Don’t write code that makes people guess, and don’t write weird code that makes people not understand, not showing off, but digging holes, and essentially junk code

var sum = 0;
function getSum(n) {
    for (var number = 0; number < n; number++) {
        sum += number;
     }
     return sum;
}
console.log(getSum(100))
Copy the code

For loops are used when we know the number of loops, and are often used to iterate over groups of numbers

Summary:

  • The for loop has a syntax structure of three expressions, given initial conditions, conditional judgments, and increment variables, which it uses when the number of loops is already known
  • If the expression is true, the statement body is executed. If it is false, the statement is broken out of the while loop. It is used when the loop continues without knowing the number of times the loop is executed, but only when a certain condition is reached
  • do- whileCycle iswhileThe deformation of a loop is grammatically related towhileThere’s similarity, which is execution before judgment, to see if the loop continuesbooleanThe expression is placed after the body of the loop. It is also used when we do not know the exact number of times the loop is executed, but only when a certain condition is reached and the loop continues or ends, but at least once

Of course, for loops are often used for traversal, and can be replaced with forEach,map, and other iterator methods

True and false in expressions are false

In the above if statement,while statement,do.. While, as well as for loops, are inseparable from conditional expressions, and the result of a conditional expression, of course, affects the execution of the statement body. The following are some practical development techniques that need to be mentioned

The following Boolean expressions all return false:

  • null
  • undefined
  • 0 // The digit 0
  • “// Empty string
  • How does NaN detect: Use the built-in Boolean object Boolean(), which returns a Boolean value. Note that this Boolean is used to initialize the value of the Boolean object

But note: all of the following return true

  • “0”. // The string is 0
  • []; / / an empty array
  • {}; / / null objects
  • Non-zero number
  • Infinity

Note: Any Boolean object that is not null and undefined, including false, is treated as true when used directly in conditional statements. With new, the body of the statement is executed, and without new, the body of the statement is not executed

var x = new Boolean(false); If (x) {// this code will be executed}Copy the code

Booleans of primitive types are not affected by this rule, as shown below

var x = false; If (x) {// this code will not execute}Copy the code

Note: Do not convert a non-boolean value to a Boolean by creating a Boolean object. Use Boolean as a conversion function, or use double! The operator

var x = Boolean(expression); Var x =!! (expression); Var x = new Boolean(expression); / / not so goodCopy the code

Boolean with new is not the same as no new. Boolean with no new returns a Boolean.

For any object, even a Boolean object with a value of false, when passed to a Boolean function, the generated Boolean object has a value of true, as shown below

var myFalse = new Boolean(false); // false var g = new Boolean(myFalse); // true var myString = new String("Hello"); var s = new Boolean(myString); // true if (myFalse) { console.log("itclanCoder"); // This statement will execute}Copy the code

The official advice is: Do not use Boolean objects where they should be used, and abuse Boolean objects. Use Boolean objects when you need to convert other types to Booleans, such as strings to Boolean types

Below is a list of notable ones

Boolean('0') == true; // true '0' ! = true // true 0 ! = null ; // true 0 == [] ; 0 == false // true Boolean(null) == false; // true null ! = true; // true null ! = false // true Boolean(undefined) == false; // true undefined ! = true; // true undefined ! = false; // true Boolean([]) == true // true Boolean({}) == true // trueCopy the code

Sometimes, when you need to exclude non-zero and null characters and false, you might write code like this

if (x ! = "" && x ! = null) {// statement body}Copy the code

The code above is not impossible, but it is redundant and can be optimized as follows

If (x) {// statement body}Copy the code

When you use a while loop, when you want the variables x not to be 0 and an empty string, and false, you might see code like this

while(x ! = null){// statement body}Copy the code

Again, it can be optimized as follows

While (x) {// statement body}Copy the code

The above code optimizations allow for null, null characters, or false, and if not true, negation

conclusion

This section mainly studies the selection control statement,if statement,switch statement,while statement and do.. While statement,for loop comparison, each statement has the corresponding application scenario and solve the problem, comparison basis

Of course, we finally learned the true and false in expressions. When we make some logical judgments at ordinary times, it is often very important to judge some boundary values