Front-end development - JavaScript conditional statement

 


The world is not only black, or white

The world is a fine gray


 ——Lungcen

 

 

Table of contents

conditional statement

if statement

if else statement

if else if else statement

 switch statement

break keyword

case clause

default statement

while loop statement

do while loop statement

for loop statement

Three expressions in a for loop

for loop nesting

for loop variant - for in

for loop variant - for of

break statement and continue statement

JavaScript tags



conditional statement


if statement

        The if statement is the simplest conditional judgment statement in the conditional judgment statement . It will execute the code content in { } only when the conditional expression is true.

    <script >
        var age = 20;
        if(age >= 18)
        { 
            alert("你已经成年");
        }
    </script>

if else statement

        An upgraded version of the if statement, a condition will only be executed when it is true in the if statement, but in daily life, there is not only one side. Just like the world is not only black, but also not only white.

        The if else statement can not only specify the code to be executed when the expression is true, but also specify the code to be executed when the expression is not true

    <script >
        var age = 20;
        if(age >= 18)
        {
            alert("成年人");
        }else
        {
            alert("未成年人");
        }
    </script>

if else if else statement

        Both if and if else statements have only one conditional expression, and the if else if else statement is their more advanced form. Multiple conditional expressions are allowed to be defined in the if else if else statement, and the corresponding code is executed according to the result of the expression .

if (条件表达式 1) {
    // 条件表达式 1 为真时执行的代码
} else if (条件表达式 2) {
    // 条件表达式 2 为真时执行的代码
}
...
  else if (条件表达式N) {
    // 条件表达式 N 为真时执行的代码
} else {
    // 所有条件表达式都为假时要执行的代码
}
    <script >
        var now = new Date();
        var dayOfWeek = now.getDay(); 
        if(dayOfWeek == 0) {           
            alert("星期日")
        } else if(dayOfWeek == 1) {
            alert("星期一")
        } else if(dayOfWeek == 2) {
            alert("星期二")
        } else if(dayOfWeek == 3) {
            alert("星期三")
        } else if(dayOfWeek == 4) {
            alert("星期四")
        } else if(dayOfWeek == 5) {
            alert("星期五")
        } else {
            alert("星期六")
        }
    </script>

 switch statement


        The switch statement can execute different codes according to different conditions . This effect is somewhat similar to the multi-branch structure of the if esle statement. However, compared with the if else multi-branch structure, the switch case statement is more concise and compact, and its execution efficiency is higher.

switch (表达式){
    case value1:
        statements1  // 当表达式的结果等于 value1 时,则执行该代码
        break;
    case value2:
        statements2  // 当表达式的结果等于 value2 时,则执行该代码
        break;
    ......
    case valueN:
        statementsN  // 当表达式的结果等于 valueN 时,则执行该代码
        break;
    default :
        statements  // 如果没有与表达式相同的值,则执行该代码
}

The switch statement compares the values ​​in the case clauses in turn based on the value of the expression:

  • If the two are equal, execute the following statement segment , and jump out of the entire switch statement when encountering the break keyword.

  • If not equal, continue to match the next case.

  • The switch statement contains an optional default keyword, and if no equal condition is found in the previous case, the statement segment following the default is executed.

break keyword

        The switch statement is executed line by line. When the switch statement finds a matching case clause, it will not only execute the code corresponding to the clause, but also continue to execute backward until the end of the switch statement.

        To prevent this, break out of the switch statement at the end of each case clause. In addition to breaking out of switch statements, break can also be used to break out of loop statements (for, for in, while, do while)

case clause

        A case clause can omit a statement, so that when a match is made, the statement in the next case clause will continue to be executed regardless of whether the condition of the next case is satisfied.

        In the switch statement, the case clause only indicates the starting point of execution, but does not indicate the end point of execution. If there is no break statement in the case clause, continuous execution will occur, thereby ignoring the conditional restrictions of the subsequent case clause, which will easily destroy the logic of the switch structure.

        So to use a switch statement in a function, you need to use a return statement (or a break statement) to terminate the switch statement to prevent the code from continuing to execute.

default statement

        default is a switch clause, which can be located anywhere in the switch, and will not affect the normal execution of multiple branches

A simple comparison between the default statement and the case statement is as follows:

  • The semantics are different: default is the default item, and case is a precedent.

  • Function extension: The default option is unique and cannot be extended. The case option is extensible without limitation.

  • Exception handling: default and case play different roles, case is used for enumeration, and default is used for exception handling.


while loop statement


The while loop evaluates the conditional expression before each iteration :

        If the result of the conditional expression is true, { }the code in the execution

        If the result of the conditional expression is false, exit the while loop and execute the code after the while loop.

var i=1;
var sum=0;
while (i <= 100){
    sum += i;
    i++;
}

        When writing a loop statement, be sure to ensure that the result of the conditional expression can be false (that is, the Boolean value false) , because as long as the result of the expression is true, the loop will continue and will not stop automatically. For this kind of condition that cannot stop automatically , we usually call it an " infinite loop" or "dead loop".


do while loop statement


The do while loop is very similar to the while loop, except that:

        The do while loop will execute the code in the loop first, and then judge the conditional expression. Therefore, regardless of whether the conditional expression is true or false, the do while loop can be executed at least once , but the while loop is different. If the conditional expression is false, it will directly exit the while loop.

do {
    // 需要执行的代码
} while (条件表达式);

It should be noted that there is a difference between the do while loop and the while loop, that is, the end of the do while loop needs to ;be terminated with a semicolon, while the while loop does not need


for loop statement


The for loop is the same as the switch statement, suitable for use when the number of loops is known

while loop and do while loop are suitable for use when you don’t know the number of loops

for(initialization; condition; increment) {
    // 要执行的代码
}

The for loop contains three optional expressions initialization, condition and increment, where:

  • initialization: declares an expression or a variable, we usually call this step "initializing the counter variable", and it will only be executed once during the loop;

  • condition: It is a conditional expression, which has the same function as the conditional expression in the while loop. It is usually used to compare with the value of the counter to determine whether to loop. The number of loops can be set through this expression;

  • increment: An expression used to update (increment or decrement) the value of the counter after each loop.

Three expressions in a for loop

 The three expressions in the brackets in the for loop can be omitted, but the semicolon used to separate the three expressions cannot be omitted

// 省略第一个表达式
var i = 0;
for (; i < 5; i++) {
    // 要执行的代码
}

// 省略第二个表达式
for (var y = 0; ; y++) {
    if(y > 5){
        break;
    }
    // 要执行的代码
}
// 省略第一个和第三个表达式
var j = 0;
for (; j < 5;) {
    // 要执行的代码
    j++;
}

// 省略所有表达式
var z = 0;
for (;;) {
    if(z > 5){
        break;
    }
    // 要执行的代码
    z++;
}

for loop nesting

Like the if else statement, no matter what kind of loop it is, it can be nested (that is, define one or more loops in a loop)

for (var i = 1; i <= 9; i++) {
    for (var j = 1; j <= i; j++) {
        document.write(j + " x " + i + " = " + (i * j) + "&emsp;");
    }
    document.write("<br>");
}

for loop variant - for in

        The for in loop is a special type of loop, and it is also a variant of the ordinary for loop. It is mainly used to traverse objects. It can be used to loop out the properties in the object in turn (note that the bad loop object is --> object)

for (variable in object) {
  // 要执行的代码
}

        variable is a variable, which will be assigned a different value each time the loop is run, and we can { }use this variable to perform a series of operations in ;

        object is the object to be traversed. In each cycle, the key of an attribute in the object object will be assigned to the variable variable until all the attributes in the object have been traversed.

// 定义一个对象
var person = {"name": "Clark", "surname": "Kent", "age": "36"};

// 遍历对象中的所有属性
for(var prop in person) {
    document.write("<p>" + prop + " = " + person[prop] + "</p>");
}

 The for in loop is created for traversing objects. Although it can also traverse arrays, it is not recommended. To traverse arrays, you can use for loop or for of loop.

for loop variant - for of

        The for of loop is a newly added loop method in ECMAScript6. It is similar to the for in loop and is also a variant of the ordinary for loop. Using the for of loop can easily traverse arrays or other traversable objects (note that the objects are—— > numeric or iterable object)

for (variable of iterable) {
    // 要执行的代码
}

        variable is a variable, which will be assigned a different value each time the loop is looped, and we can { }use this variable to perform a series of operations in the following;

        iterable is the content to be traversed, in each loop, a value in iterable will be assigned to the variable variable until all the values ​​in iterable have been traversed.

// 定义一个数组
var arr = ['a', 'b', 'c', 'd', 'e', 'f'];
// 使用 for of 循环遍历数组中的每个元素
for (var value of arr) {
    document.write(value + ", ");
}
document.write("<br>");
// 定义一个字符串
var str = "Hello World!";
// 使用 for of 循环遍历字符串中的每个字符
for (var value of str) {
    document.write(value + ", ");
}
document.write("<br>");
// 定义一个对象
var obj = {"name": "Clark", "surname": "Kent", "age": "36"};
// 使用 for in 循环遍历对象中的所有属性
for(var value in obj) {
    document.write(value + ", ");
}

Although the for of loop can also traverse the object, it is not recommended. To traverse the object, you can use the for in loop.

break statement and continue statement

        Break Statement The break statement has been briefly understood before, and the break statement can be used to jump out of the switch statement. In fact, using the break statement can also be used to jump out of the loop.

        The continue statement is used to skip this loop and execute the next loop . When a continue statement is encountered, the program will immediately retest the conditional expression, and if the result of the expression is true, it will start the next loop, and if the result of the expression is false, it will exit the loop.

JavaScript tags

        A tag in JavaScript is different from a tag in HTML, in that a tag in JavaScript is an identifier (like a variable name) followed by a colon  .

        JavaScript tags can be declared before any statement or code block, and cooperate with break or continue to jump out of a specific loop. For example, when multiple loops are nested, using break alone can only jump out of the current loop, but cannot jump out of the outer loop. If you use break with labels, you can break out of multiple loops at once .

outerloop:          // 定义一个标签    
for (var i = 0; i < 5; i++) {
   document.write("外层循环: " + i + "<br />");
   innerloop:       // 定义一个标签
   for (var j = 0; j < 5; j++) {
      if (j > 3 ) break ;           // 跳出内层循环
      if (i == 2) break innerloop;  // 跳出内层讯息
      if (i == 4) break outerloop;  // 跳出外层循环
      document.write("内层循环: " + j + " <br />");
   }
}      
document.write("循环结束!<br /> ");

Note: 1. There cannot be a newline between break or continue and the label

           2. No other codes can appear between the label name and the relevant cycle.

 


The world is not only black, or white

The world is a fine gray


 ——Lungcen

Guess you like

Origin blog.csdn.net/qq_64552181/article/details/129905197