Detailed explanation of operators, expressions and statements based on JavaScript

Posted by afatkidrunnin on Mon, 06 Dec 2021 23:54:09 +0100

JavaScript basics 02

operator

Arithmetic operator

Mathematical operators are also called arithmetic operators, including addition (+), subtraction (-), multiplication (*), division (/), and remainder (%) (modulo).

() the priority can be raised, and its priority is the same as that calculated in mathematics. Multiply and divide first, then add and subtract, and parentheses take priority

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

<body>
    <script>
        console.log(4 / 2)//Output 2
        console.log(4 % 2)//Output 0
        console.log(2 % 4)//Output 2
        console.log(5 % 8)//Output 5
    </script>
</body>

</html>

Assignment Operators

=Assign the value to the right of the equal sign to the left of the equal sign. The left must be a container

+=Add the value on the right of the symbol to the value on the left and assign the value on the left

-=After the value on the right of the symbol meets the value on the left, assign the value on the left

/=Divide the value on the left of the symbol by the value on the right and assign the value on the left

%=After the value on the left of the symbol is subtracted from the value on the right, the value on the left is given

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

<head>
</head>

<body>
    <script>
        // Add i to sum with two variables
        let i = 1
        let sum = 0
        // sum = sum + i
        sum += i
        let num1 = 10
        num1 /= 2
        console.log(num1); //Output 5
    </script>
</body>

</html>

Unary operator

Unary operators can make variables increase or decrease or negate!

Define a variable num,num++,++num is self increasing, num –, -- num is self decreasing

Pre auto increment: + num auto increment before use

Post auto increment: num + + is used first and then auto increment

In general, post auto increment is often used in development

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

<head>
</head>

<body>
    <script>
        // Pre autoincrement
        // let i = 1
        // Self addition before use
        // console.log(++i + 2)  // 4
        // Post auto increment
        let i = 1
        // First use and then self add
        console.log(i++ + 2) // The output is 3
        console.log(i)//The output is 2 and has been self incremented
    </script>
</body>

</html>

Comparison operator

>: is the left greater than the right

<: is the left smaller than the right

>=Is the left greater than or equal to the right

< =: is the left less than or equal to the right

==: are the left and right sides equal

===: whether the left and right types and values are equal

!==: Are the left and right sides incomplete

The comparison result is of boolean type, that is, only true or false will be obtained

The comparison operator is actually the ASCII code corresponding to the comparison character

NAN is not equal to any value, including itself

Try not to compare decimals, because decimals have precision problems

The comparison between different types will be implicitly converted to number type for comparison

Therefore, in the development, we prefer = = = or if we make an accurate comparison==

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

<head>
</head>

<body>
    <script>
        console.log(3 > 5) // Output false
        console.log(5 >= 5) // Output true
        // console.log(5 = 5)
        console.log(5 == 5)//Output true
        // ==As long as the value is the same, it is true regardless of the data type
        console.log(5 == '5')//Output true
        console.log(5 == 'pink')//Output false
        // ===In the future, it is necessary to use = = = to develop common required values and data types
        console.log(5 === 5)//Output true
        console.log(5 === '5')//Output false
        // exceptional case
        console.log('pink' > 'red')//Output true
        console.log('pink' > 'pin')//Output false
        console.log(1 === NaN)//Output false
        console.log(NaN === NaN)//Output false
        console.log(0.1 + 0.2 === 0.3)//Output false
        console.log(0.1 + 0.2)//Output 0.3000000004

        console.log(3 > '2')
    </script>
</body>

</html>

Logical operator

Use of logical operators

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-unil7hi1-1638790212198) (assets / 163876231386. PNG)]

Short circuit in logical operator

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-tBUcYwkX-1638790212199)(assets/1638762483140.png)]

Operator priority

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-jiyh78jn-1638790212200) (assets / 163876247054. PNG)]

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-NrmeBSXV-1638790212200)(assets/1638762568302.png)]

sentence

Expressions and statements

An expression is a collection of codes, which is evaluated as a result by the js interpreter,

Statements are js whole sentences or commands, such as if statements and for loop statements

Expression: 3 + 4

sentence:

alert() pop up dialog box, if statement, for statement, switch statement

In fact, in some cases, an expression can also be understood as a statement, because it is calculating the result and doing things

Branch statement

In the code we wrote before, we executed a few sentences from top to bottom after writing a few sentences. This is called sequential structure

Sometimes the execution code is selected according to the conditions, which is called branch structure

When a piece of code is repeatedly executed, it is called a loop structure

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (IMG ltjooynp-1638790212200) (assets / 1638763715645. PNG)]

if branch statement

if statements can be used in three ways: single branch, double branch and multi branch

Single branch

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-jiuhh7eu-1638790212200) (assets / 16387638616. PNG)]

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

<head>
</head>

<body>
  <script>
    //Pop up box to collect user information and convert it to digital type
    let score = prompt('Enter your college entrance examination scores') * 1
    //If the score is greater than or equal to 700, the pop-up box
    if (score >= 700) {
      alert('Congratulations on your admission to Tsinghua University')
    }
  </script>
</body>

</html>
Double branch

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (IMG ayrqdfsv-1638790212201) (assets / 1638771806662. PNG)]

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

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    //Pop up box to collect user information and convert it to digital type
    let score = prompt('Enter your college entrance examination scores') * 1
    //If the score is greater than or equal to 700, the pop-up box
    if (score >= 700) {
      alert('Congratulations on your admission to Tsinghua University')
    }
    Otherwise, pop-up frame...
    else {
       alert('It's a pity,You lost the list.')
    }
  </script>
</body>

</html>
Multi branch

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-s0xdSCFz-1638790212201)(assets/1638771831597.png)]

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

<head>
</head>

<body>
    <script>
        // 1. The user can input the time and obtain the time automatically in combination with api
        let time = prompt('Please enter the hour:')
        // 2. Multi branch judgment
        if (time < 12) {
            document.write(`Good morning, good work`)
        } else if (time < 18) {
            document.write(`Good afternoon, good work`)
        } else if (time < 20) {
            document.write(`Good evening. Work overtime`)
        } else {
            document.write(`It's late at night. Do you have any hair?`)

        }
        // 12 - 18 PM
        // The time we input should be greater than 12 and less than 18
        // time >12 && time < 18
    </script>
</body>

</html>

Ternary operator

Syntax: [the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-EZYwX9eA-1638790212201)(assets/1638772591863.png)]

It is generally used to take values, which can simplify the code of double branch statements

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // console.log(true ? 1 : 2)
        // console.log(false ? 1 : 2)

        // if (3 > 5) {
        //     alert('first ')

        // } else {
        //      alert('second ')
        // }
			 //The above statement can be simplified to the following one
        // 3 > 5 ?  alert('first '): alert('second')
        let num1 = 40
        let num2 = 30
        // num1 > num2 ? console.log(num1) : console.log(num2)
			 //Requirement: the user enters 1 number. If the number is less than 10, 0 will be added in front, such as 09, 03, etc
        // let re = num1 > num2 ? num1 : num2
        let re = num1 > num2 ? num1 : num2
        console.log(String('0' + num1))

        console.log(re)
        // let re = 3 + 5
    </script>
</body>

</html>

swich statement

grammar

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-azg1hnda-1638790212202) (assets / 163877450592. PNG)]

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-IvIPmkEm-1638790212202)(assets/1638774542907.png)]

  1. switch case statements are generally used for equivalence judgment and are not suitable for interval judgment

  2. Switch cases are generally used with the break keyword. No break will cause case penetration. When running to break, the cycle will end directly

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

<head>
</head>

<body>
    <script>
        // 1. There is another operator when the user enters a number
        let num1 = +prompt('Please enter the first number:')
        let num2 = +prompt('Please enter the second number:')
        let sp = prompt('Please enter+ - * / operation')
        // 2. Calculate different result switch es according to different operators
        switch (sp) {
            case '+':
                alert(`You chose to add, and the result is: ${num1 + num2}`)
                break
            case '-':
                alert(`You selected subtraction and the result is: ${num1 - num2}`)
                break
            case '*':
                alert(`You chose multiplication and the result is: ${num1 * num2}`)
                break
            case '/':
                alert(`You chose division and the result is: ${num1 / num2}`)
                break
            default:
                alert(`What did you lose? Please enter+ - * / `)
        }
    </script>
</body>

</html>

Circular statement

Browser debugging method

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-nAsPpUD2-1638790212202)(assets/1638776752688.png)]

while Loop

while loop syntax

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-PfqkAqhU-1638790212203)(assets/1638776961419.png)]

Similar to the if statement, the code will be executed only when the condition in parentheses is true

After the code in the while braces is executed, it will not jump out, but continue to return to the braces to judge whether the conditions are met. If so, execute the code in the braces, and then return to the braces to judge the conditions until the conditions in the braces are not met, that is, jump out

The cycle needs to have three elements:

  1. Variable starting value

  2. Termination condition (if there is no termination condition, the loop will be executed all the time, resulting in an endless loop)

  3. Variable variation (self increasing or self decreasing)

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

<head>
</head>

<body>
    <script>
        // Cycle must have 3 elements
        // Start value of variable
        let i = 1
        // Termination conditions
        while (i <= 3) {
            document.write(`Monthly salary over 10000 <br>`)
            // Variable change
            i++
        }
    </script>
</body>

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

<head>
</head>

<body>
    <script>
        // 1. Output 1 ~ 100 numbers
        // Starting value
        // let i = 1
        // //Termination conditions
        // while (i <= 100) {
        //     Document. Write (` < p > Yes: ${I} < / P > `)
        //     //Variable change
        //     i++
        // }

        // 2. Calculate the sum of 1 ~ 100 and 1 + 2 + 3 +.. + 100
        // let j = 1
        // let sum = 0
        // while (j <= 100) {
        //     // sum = sum + j
        //     sum += j
        //     j++
        // }
        // console.log(sum)  // 5050

        // 3. Find the even cumulative sum between 1 and 100
        let i = 1
        let sum = 0
        while (i <= 100) {
            if (i % 2 === 0) {
                // i must be even at this time
                sum = sum + i
            }
            // Whether you are even or odd, I want it++
            i++
        }
        console.log(sum)
    </script>
</body>

</html>   
Loop exit

End of cycle:

Continue: end this cycle and continue the next cycle

break: jump out of the loop

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        while (true) {
            let str = prompt('If it were me DJ,do you still love me?')
            if (str === 'love') {
                alert('I love you too~~')
                break
            }
        }
    </script>
</body>

</html>

Comprehensive case

Page pop-up

Requirement: a dialog box will pop up on the page, 'do you love me'; if you enter 'love', it will end; otherwise, the dialog box will pop up all the time

analysis:

① : the loop condition is always true, and the dialog box always pops up

② : let the user input again during the loop

③ : if the user enters: love, exit the loop (break)

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

<head>
</head>

<body>
  <script>
    //Define an initial amount variable
    let money = 100

    //If the user does not choose to exit, the pop-up box will always pop up for the user to operate
    while (1) {
      //Define a variable to obtain the operation sequence number desired by the user
      let enterNum = prompt(`Please select your action:
          1.withdraw money
          2.deposit
          3.View balance
          4.sign out`) * 1
      //If you select 4 exit, exit the while loop
      if (enterNum == 4) {
        break//Exit loop
      }
      switch (enterNum) {
        case 1: {
          let outMoney = prompt('Please enter the amount you want to withdraw:') * 1
          //Judge that the amount cannot be less than the existing amount. If it is less than, the warning box will pop up
          if (outMoney <= money) {
            money -= outMoney
          } else {
            alert(`Your current deposit is ${money}element,Please enter a withdrawal amount less than it`)
          }
          break
        }
        case 2: {
          let inMoney = prompt('Please enter the amount you want to deposit:') * 1
          money += inMoney
          break
        }
        case 3: {
          alert(`Your current deposit is ${money}element`)
          break
        }
      }
    }
  </script>
</body>

</html>

Topics: Javascript Front-end