javascript flow control statement (2)

Operator

Operators are also called operators, which are used to implement assignments, comparisons, and perform arithmetic operations.

javascript common operators

  • Arithmetic Operator
  • Comparison operator
  • Logical Operators
  • Assignment operator
  • Increment and decrement operators

Arithmetic Operator

Used to perform arithmetic operations on two variables or values

<script>
    // 算数运算符包括加减乘除 取余等等
    console.log(1 + 1);
    console.log(2 - 1);
    console.log(1 * 6);
    console.log(6 / 3);
    console.log(6 % 3);

    // 在算数运算符中 浮点数的精度会产生细微的差距,不要拿两个浮点数相比较
    console.log(0.1 + 0.2);
    console.log(0.7 * 100);

    console.log(0.1 + 0.2 == 0.3)
</script>

Insert picture description here

Precautions

  • In js, two floating-point numbers cannot be directly compared
  • In the order of operations in js, multiplication and division are calculated first, followed by addition and subtraction. If there are parentheses, the parentheses are calculated first.

How to judge whether a number can be divisible?

余数为0 说明这个数可以被整除

expression

A formula composed of numeric operator identifiers is called an expression

return value

The expression eventually returns a result to us, this result is called the return value

     var  num = 1 + 1 
上述代码中,这样的式子便叫做表达式,右边的公式计算完毕后有一个返回值,这个返回值赋值给左边的num

Unary operator

Unary operators are divided into pre-type and post-position type. They are mainly used to realize the increment and decrement operations of variables and must be used in conjunction with variables.

Preposition operator

Pre-type operators first increment (decrement) and then perform operations

Pre-increment operator: Increment first, then perform operations


    <script>
        //前置型运算符 先自增(自减) 再进行运算
        var num = 10;
        ++num;
        console.log('num的值:', num) //11

        var num2 = ++num + 5;
        console.log('num2的值:', num2) //17
    </script>

Insert picture description here

Pre-decrement operator: decrement first, then perform the operation

 <script>
        //前置自减运算符  
        var num = 20;
        --num;
        console.log('num的值:', num); //19

        var num2 = --num + 5;
        console.log('num2的值', num2); //23
    </script>

Insert picture description here

Post operator

Calculate the original value first, and then perform the increment or decrement operation

Post-increment operator: calculate the original value first, and then auto-increment xi

<script>
    //后置型自增运算符  先原值运算,再自加
    var num = 2;
    num++;
    console.log('num的值:', num); //3

    var num2 = num++ + 2;
    console.log('num2的值:', num2) //5

    var num3 = num++ + 1;
    console.log('num3的值:', num3) //5
</script>


Insert picture description here

Post decrement operator: calculate the original value first, then decrement


<script>
    //后置自减运算符 进行原值计算 再自增
    var num = 6;
    num--;
    console.log('num的值:', num); //5

    var num2 = num-- + 1;
    console.log('num2的值为:', num2); //6

    var num3 = num-- + 1;
    console.log('num3的值:', num3); //5
</script>

Insert picture description here

Comprehensive exercises of unary operators


    <script>
        //第一题
        var a = 5;
        ++a;
        var b = ++a + 6;
        console.log('b的值:', b); //13


        //第二题
        var c = 10;
        c++;
        var d = c++ + 2;
        console.log('d的值:', d); //13


        // 第三题
        var e = 10;
        var f = e++ + ++e; //首先e++是10 然后自增1 于是++e变成12  所以值为22=10+12
        console.log('f的值:', f) //22
    </script>



Insert picture description here

Summary of unary operators

  • The unary operator is to simplify the code operation, mainly to make the variable realize the self-increment or self-decrement operation
  • No difference when used alone
  • Pre-increment operator and pre-decrement operator: first increment (decrement), and then calculate
  • Post-increment operator and post-increment operator: operate on the original value first, and then increase (decrease)
  • In the actual development process, more post operators are used

Comparison operator

The comparison operator (relational operator) is mainly used to compare two data operators, which will return a Boolean value as the result of the comparison operation

Insert picture description here



<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        //比较运算符 是用来进行两个数据的比较所使用的运算符 得出的结果为布尔值
        console.log(5 > 3) //true
        console.log(6 < 7) //true
        console.log(6 >= 5); //true 解析:因为6大于5  所以正确
        console.log(7 <= 8); //true 解析:因为7小于8 所以正确

        console.log(8 == '8') //true 解析:比较值而不比较数据类型
        console.log(8 != 9); //true
        console.log(8 !== 8) //false 
        console.log(8==="8") //false 解析:===要求数据类型和值都相等
    </script>
</head>




Insert picture description here

Logical Operators

Logical operators are operators used to perform Boolean operations, and the result is also a Boolean value. In actual development, it is mostly used to judge multiple conditions


    <script >
        /* 
         *    逻辑运算符:是用来比较布尔值运算的运算符,其结果也是布尔值,开发中常用于多重条件的判断
         */
        console.log(5 > 3 && 3 < 5); //true 
        console.log(5 < 3 && 3 < 7); //false

        console.log(5 < 7 || 5 < 3); //true
        console.log(5 < 7 && 5 < 3) //false

        console.log(!true) //false
        console.log(!false) //true
    </script>



Insert picture description here

Summary of logical operators

  • &&: If both sides are true, the result will be true, and there is a false on both sides, and the result will also be false
  • ||: If both sides are false, the result will be false. If there is a true on both sides, the result will also be true;
  • !:Negate! The result of true is false

Summary of logical operators


    <script>
        var num = 7;
        var str = "我爱你,亲爱的中国"
        console.log(num > 5 && num <= str.length) //true
        console.log(num < 5 && num <= str.length) //false

        console.log(!(str.length > 11)) //true
        console.log(!(num > 5 || str.length == num)) //fase
    </script>


Insert picture description here

Short circuit effect

When there are multiple expressions (values), if the value of the expression on the left can be determined, the value operation of the expression on the right will not be performed.

Logical AND of logical interrupt

Insert picture description here

  <script>
        console.log(234 && 456); //456
        console.log(0 && 440) //0
        console.log('' && 254 && 546); //""
    </script>

Insert picture description here

Logical OR of logical interrupt

Syntax: expression 1 || expression 2

  • If expression 1 is true, return the value of expression 1
  • If expression 1 is false, return the value of expression 2 (can be compared with logical AND)
	<script>
        console.log(234 || 456); //234
        console.log(0 || 440) // 440
        console.log('' || 254 || 546); //254
    </script>

Insert picture description here

Assignment operator

Operator that assigns data to variables, referred to as assignment operator

Insert picture description here

  <script>
        var num = 20;
        num += 5;
        console.log(num); //25


        var num2 = 6;
        num2 *= 6;
        console.log(num2) //36

        var num4 = 20;
        num4 %= 4;
        console.log(num4) //0
    </script>

Insert picture description here

Operator precedence

Insert picture description here

  • The unary operator! Has a high priority
  • Logical AND is higher than logical OR

Exercises of operator sequence (1)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>练习1</title>
</head>

<body>

</body>
<script>
    console.log(4 >= 6 || '人' != '阿凡达' && !(12 * 2 == 144) && true)
        /* 
        解析:4 >= 6 || '人' != '阿凡达' && true && true
            false|| true && true && true
             true
        结果:true
            
         */

    var num = 10;
    console.log(5 == num / 2 && (2 + 2 * num).toString() === '22')
    /*

    * 解析:5==num/2&&(2+2*num).toString()==='22'
            5==num/2&&'22'==='22'
            5==5&&'22'==='22'
            true
     结果:true

     */
</script>

</html>

Insert picture description here

Exercises of operator sequence (2)


    <script>
        var a = 3 > 5 && 2 < 7 && 3 == 4;
        console.log(a)
            /* 
            解析:a=false && true && false
            结果:a= false
             */



        var b = 3 <= 4 || 3 > 1 || 3 != 2
        console.log(b);
        /* 
            解析:b= 3 <= 4 || 3 > 1 || 3 != 2
                  b= 3 <= 4 || 3 > 1 || true
                  b= true || true || true
            结果:true
         */



        var c = 2 === "2"
        console.log(c);
        /* 
            解析:=== 用来比较数据类型和值是否相等  所以为false
         */


        var d = !c || b && a;
        console.log(d)
            /* 解析: d = !c ||b && a;
                      d = true||b && a;
                      d = true||true && false;
                      d= true
               结果为true

             */
    </script>


Insert picture description here

Flow control statement

Simply put, it means that the control code sequence is executed in a different structural sequence

Flow control statement: sequence structure branch structure loop structure

Sequence structure of flow control statements

In javascript, the execution order of the code is executed sequentially from top to bottom, and this order of execution is called sequential structure

Branch structure

During the execution of the code from top to bottom, the code on different paths is executed according to different conditions to obtain different results.

Insert picture description here

Two branch structures are provided in javascript

  • if statement
  • switch statement

if statement

grammar

if(条件表达式) {
	//执行的语句
	}

Note: If the conditional expression is true, the statement will be executed; if the conditional expression is false, the statement will not be executed
Insert picture description here

   <script>
        if(true) {
            console.log('条件表达式为真,则执行语句');
        }

        if(false) {
            console.log('条件表达式为假,则不执行语句');
        }
    </script>

Insert picture description here

if double branch statement

Insert picture description here
grammar

 if(条件表达式) {
        //执行的语句
    }else {
        //执行的语句
    }

Precautions

  • Only one statement in if and else can be executed
  • Nothing after else {}

Internet cafe case of if double branch statement

 要求:弹出一个输入框,用户输入自己的年龄,如果大于等于18岁,提示可以进入网吧,如果小于18,则提示用户不能进入网吧

The idea is as follows

  • 1. Pop up the input box and save the value entered by the user as a variable
  • 2. Use if statements to make judgments, and execute different statements according to the age of the user.


    <script>
        var userName = Number(prompt("请输入年龄")); //Number():将字符串类型转换成Number类型
        if (userName >= 18) {
            alert("恭喜你,可以进入网吧")
        } else {
            alert("对不起,你不能进入网吧")
        }
    </script>

Insert picture description here

Judgment of if double-branch statement leap year and normal year

提示:能被4整除且不能整除100的为闰年(如2004年就是闰年,1901年不是闰年)或者能够被 400 整除的就是闰年

The idea is as follows

  • 1. The user enters the year and saves the value entered by the user in the form of a variable
  • 2. Use if statements to judge leap years and normal years according to different conditions

    <script>
        var userName = Number(prompt("请输入年份"));
        if (userName % 4 == 0 && userName % 100 != 0 || userName % 400 == 0) {
            alert("闰年")

        } else {
        
            alert('平年')


        }
    </script>

Insert picture description here

if multi-branch statement

Scenario: Applicable to the judgment of multiple conditions


if(条件表达式1) {
    语句1;
}else if(条件表达式2) {
    语句2;
}else if(条件表达式3) {
    语句3;
    .....
}else {
    //以上代码不成立执行此处代码
}

Precautions

  • According to different conditions, different code paths are executed, and the final result is obtained. It is a process of choosing one more than one.
  • Conditional expression is added after else if, and there is no conditional expression after else
Achievement case of if multi-branch statement

Insert picture description here



    <script>
        var source = Number(prompt("请输入分数"))
        if (source >= 90) {
            alert('A')
        } else if (source >= 80) {
            alert('B')
        } else if (source >= 70) {
            alert('C')
        } else if (source >= 60) {
            alert("D")
        } else {
            alert('E')
        }
    </script>




Insert picture description here

Ternary expression

Ternary expressions can do some simple conditional judgments. The formulas composed of ternary operators are called ternary expressions.

The syntax is as follows

Conditional expression? Expression 1: Expression 2 If the conditional expression is true, it returns the value of expression 1, and if the conditional expression is false, it returns the value of expression 2


   
   

Insert picture description here

The complement of ternary expression 0

Ternary expression must be used

The idea is as follows

  • 1. An input box pops up, and the user enters a number between 0 and 59
  • Add 0 to the front of the number between 2.0~9, and do nothing for numbers greater than 10
  • 3. Use variables to accept a return value and output (processed inside the program)
    <script>
        var userName = Number(prompt("请输入1~59之间的数字"))

        var result = userName <= 9 ? '0' + userName : userName;
        alert(result)
    </script>



Insert picture description here

switch statement

The switch statement is a multi-branch statement, and executing different conditional statements to get different results is a process of choosing one.

Precautions

  • The if multi-branch statement is only used for judgment, and the switch statement is mainly suitable for specific value matching
  • switch: switch. case: option.
  • If the value of the variable after the switch statement is congruent with the value after the case, the statement after the case is executed
  • If the value is not matched, execute the statement following default
  • The expression after the switch statement is a variable.
  • Don't forget to write break, otherwise it will always be executed.
Fruit case of switch statement

Requirement: The user enters the fruit he needs, and the price of the fruit is displayed on the screen.

The idea is as follows

  • An input box pops up, and the user needs their desired fruit
  • Save the value entered by the user in the form of a variable. When the value of the conditional expression after the switch matches the value after the case, the corresponding fruit price will pop up
  • Don't forget to break, otherwise the program will continue to execute.


    <script>
        var fruit = prompt('请输入需要的水果');
        switch (fruit) {
            case "苹果":
                alert("苹果3.5/斤");
                break;
            case "香蕉":
                alert("香蕉5.5/斤");
                break;
            case "榴莲":
                alert("榴莲10.5/斤");
                break;
            default:
                alert("找不到此水果")
        }
    </script>


Insert picture description here

The difference between switch statement and if else if statement

  • The switch is used for specific value matching, and the if else statement is used for conditional judgment
  • After the switch determines the value, it is executed directly into the program, and the if statement has to be judged in turn (the execution efficiency is slightly lower)
  • In the case of fewer branches, using if else is more efficient

Guess you like

Origin blog.csdn.net/weixin_45419127/article/details/111215553