Basic Javascript (operator and process control)

Keywords: Javascript html5 pink

1. Operator (operator)

"Operator" is a symbol used to realize the functions of assignment, comparison and arithmetic operation. Common operators are classified as follows 👇

  • Arithmetic operator

  • Increment and decrement operators

  • Comparison operator

  • Logical operator

  • Assignment Operators

1.1 arithmetic operators

operatordescribecase
+plus10+20=30
-reduce10-20=-10
*ride10*20=200
/except10/20=0.5
%Surplus (mold taking)Returns the remainder of division 9% 2 = 1
  //alert(1 + 1);
        console.log(1 + 1);  //You should type a space on both the left and right sides of the operator
        //alert(1 - 1);         //0
        //alert(1 * 1);         //1
        //alert(1 / 1);         //1

1.% surplus (mold taking)

//alert(4 % 2);           //0
 //alert(5 % 3);           //2
//alert(3 % 5);           //3 attention!!!!!!!!!!

2. There will be problems in floating-point arithmetic

  var result = 0.1 + 0.2;    //  The result is not   0.3, but 0.300000000000000 4
  console.log(0.07 * 100);   //  The result is not 7,    Instead: 7.000000000000001

    The highest precision of floating-point numbers is 17 decimal places, but its precision is far less than that of integers, so don't directly judge whether two floating-point numbers are equal!

3. We can't compare floating point numbers directly   Are they equal

 var num = 0.1 + 0.2;
 alert(num == 0.3);          //false to convert to binary, there will be an error in accuracy
  • Expressions and return values

    • Expression: an expression consisting of numbers, operators, and variables.

    • Return value: each expression will have a final result after corresponding operation, which is called the return value of the expression

  // Is a formula composed of numbers, operators, variables, etc. we call it expression 1 + 1
 // alert(1 + 1);  //2 is the return value

    //Writing method
    //1 + 1=2
    // In our program, 2 = 1 + 1 calculates the expression on our right and returns the value to the left
    var num = 1 + 1;
    // alert(num);  //2

1.2 increment and decrement operators

If you need to add or subtract 1 from a numeric variable repeatedly, you can use the increment (+) and decrement (- -) operators.

In javascript, the increment (+) and decrement (- -) operators can be placed either before or after variables. When placed in front of a variable, it is called the pre increment (decrement) operator, and after it is the post increment (decrement) operator

  Note: increment and decrement operators must be used with variables.

The prefix increment operator uses the formula: first add, and then return the value

 <script>
        //1. It is troublesome to add 1 num = num + 1 to a variable
        var num = 1;
        num = num + 1; // ++num
        num = num + 1;
        //alert(num);  //3

        //2. The pre increment operator + + is written in front of the variable
        var age = 20;
        ++age; //Similar to age = age + 1
        //alert(age);  //21

        // 3. Add 1 first and then return the value
        var p = 10;
        alert(++p + 10); //21
    </script>

  The prefix increment operator uses the formula: return the original value first   Add 1 after

 <script>
        var num = 10;
        num++; // num = num + 1  ++num
        // alert(num);         //11
        //1. If the pre auto increment and post auto increment are used separately, the effect is the same
        //2. Post auto increment formula: first return the original value and then add 1
        var age = 10;
        //alert(age++ + 10);   //20
        //alert(age);         //11
        //alert(age + 10);    //21
    </script>

Case:

 <script>
        var a = 10;
        ++a; //++A = 11 A = 11 + + A is an expression
        var b = ++a + 2; // A = 12 A + + = 12 pre: add first and then return the value
        //alert(b);   //14  


        var c = 10;
        c++; //c++ = 11  c = 11
        var d = c++ + 2; //C + + = 11 C = 12 post: return the original value first, and then add it automatically
        //alert(d);                 //13

        var e = 10;
        var f = e++ + ++e; // e++ =10  e=11  ++e=12
        console.log(f); //22


        // The subsequent self increment expression returns the original value, and the subsequent variable is self incremented by 1
        // Pre auto increment: self addition before operation
        // When used alone, the operation results are the same
        // During development, most of them use post increment / decrement, and the code is exclusive on one line, such as num + +; Or num--
 </script>

1.3 comparison operators

      The comparison operator is the operator used when comparing two data. The comparison operator will return a Boolean value (true/false) as the result of the comparison operation.

operatordescribecaseresult
<Less than sign1<2true
>Greater than sign1>2false
>=Greater than or equal to sign (greater than or equal to)2 >= 2true
<=Less than or equal to sign (less than or equal to)3 <= 2false
==Equal sign (transformation)15 == '15'true
!=Unequal sign37 != 37false
===    !===Congruent and unequal (required values and data types are consistent)37 === '37'false
<script>
        // alert(3 >= 5);  //false
        // alert(2 <= 5);     //true

        //1. The equal sign in our programmers is = = the default conversion data type will convert string data to number data
        // As long as the evaluation is relative
        //alert(3 == 5);                     //false
        //alert('pink teacher '= =' Andy Lau ')// false 
        //alert(18 == 18);                    //true
        //alert(18 == '18');                  //true
        //alert(18 != 18);                    //false   !=   Not equal to


        //2. we programmers as like as two peas in the same order, and the data type is exactly the same, so we can true.
        //alert(18 === 18);             //true
        //alert(18 === '18');           //false 
</script>
Symboleffectusage
=assignmentGive the right to the left
==judgeJudge whether the values on both sides are equal (note that there is implicit conversion at this time)
===CongruentJudge whether the values and data types on both sides are exactly equal

1.4 logical operators

Concept: a logical operator is an operator used for Boolean operations, and its return value is also a Boolean value. In the later development, it is often used to judge multiple conditions

 <script>
        // 1. If both sides of logic and & & (and) are true, the result is true. As long as the result on one side is false, the result is false
        //alert(3 > 5 && 3 > 2);   //false
        //alert(3 < 5 && 3 > 2);     //true

        // 2. If both sides of logic or | (or) are false, the result is false. As long as one side is true, the result is true
        //alert(3 > 5 || 3 > 2);    //true
        //alert(3 > 5 || 3 < 2);    //false

        //3. Logical non! (not)
        alert(!true); //false
    </script>

practice:

   <script>
        var num = 7;
        var str = "I love you!~China~";

        alert(num > 5 && str.length >= num); //true

        alert(num < 5 && str.length >= num); //false

        alert(!(num < 10)); //false

        alert(!(num < 10 || str.length == num)); //false
    </script>

Short circuit operation (logic interrupt): (js API)

When there are multiple expressions (values) and the expression value on the left can determine the result, the operation of the expression value on the right will not be continued;

  3. Logic and short circuit operation returns expression 2 if the result of expression 1 is true, and expression 1 if expression 1 is false
        alert(123 && 456);              //456 all numbers are true except 0
        alert(0 && 456);                // 0
        alert(0 && 1 + 2 && 456 * 56789); // 0
        alert('' && 1 + 2 && 456 * 56789); // ''
        If the empty or negative is false, the rest is true    :  0  ''  null undefined  NaN
 4. Logical or short circuit operation returns expression 1 if the result of expression 1 is true and expression 2 if the result of expression 1 is false
        alert(123 || 456); // 123
        alert(123 || 456 || 456 + 123); // 123
        alert(0 || 456 || 456 + 123); // 456
Logical interrupt is very important. It will affect the running result of our program
        var num = 0;
        //alert(123 || num++);      // 123 num + + will not run
        //alert(num);                 // 0

1.5 assignment operator

operatordescribecase
=Direct assignmentvar userName = 'fan'
+= -=Add or subtract a number before assigning a valuevar age=5; age+=5
*= /= %=Assign value after multiplication, division and modulusvar age=5; age*=5
  <script>
        var num = 10;
        // num = num + 1;   //num++
        // num = num + 2        //num+=2;

        var num = 10;
        num += 5;
        // alert(num);   //15

        var num = 10;
        num -= 5;
        // alert(num);   //5


        var age = 2;
        age *= 3;
        // alert(age);     //6

        var age = 6;
        age /= 3;
        // alert(age);     //2

        var age = 4;
        age %= 2;
        // alert(age);     //0
    </script>

1.6 operator priority

priorityoperatororder
1parentheses()
2Unary operator! ++ --
3Arithmetic operator First * /% then +-
4Relational operator> >= < <=
5Equality operator== != === !==
6Logical operatorFirst & & then||
7Assignment Operators =
8Comma Operator ,
  <script>
        //  Unary operator: + num! Num binary operator: 2 + 3
        // Exercise 1
        console.log(4 >= 6 || 'people' != 'Avatar' && !(12 * 2 == 144) && true) //true
        var num = 10;
        console.log(5 == num / 2 && (2 + 2 * num).toString() === '22'); //true
        console.log('-------------------');
        // Exercise 2
        var a = 3 > 5 && 2 < 7 && 3 == 4;
        console.log(a); //false

        var b = 3 <= 4 || 3 > 1 || 3 != 2;
        console.log(b); //true

        var c = 2 === "2";
        console.log(c); //false

        var d = !c || b && a;
        console.log(d); //true
    </script>

2. Process control

"Process control" during the execution of a program, the execution order of each code has a direct impact on the result of the program. Many times we need to control the execution order of the code to realize the functions we want to complete. There are three main structures of process control, namely sequence structure, branch structure and loop structure, which represent the execution order of the three codes.

Branch process control:

two point one   Syntax structure of if

        if (Conditional expression) {
            //Execute statement
        }
        2. Implementation idea if
        if The result of the conditional expression is true true Execute the execution statement in braces
        If if If the result of the conditional expression is false, the statement in braces will not be executed if Code after statement
        3. Experience Code:
        if (3 < 5) {
            alert('Desert camel ');
        }

Case:

  <script>
        // The prompt input box pops up, the user enters the age, and the program takes this value and saves it in the variable
        // Use the if statement to judge the age. If the age is greater than 18, execute the output statement in the if braces
        var age = prompt('Please enter age');
        if (age >= 18) {
            alert('You can enter the Internet cafe')
        }
    </script>

2.2 if   else double branch statement

<script>
        // 1. Syntax structure if else otherwise
        // if (conditional expression){
        //     //Execute statement 1
        // } else {
        //     //Execute statement 2 
        // }

        // 2. Execution idea if the expression result is true, execute statement 1; otherwise, execute statement 2
        // 3. Code verification
        var age = prompt('Please enter your age:');
        if (age >= 18) {
            alert('I want to take you to the Internet cafe to steal headphones');
        } else {
            alert('Go home and do your homework');
        }
        // 5. Statement 1 in if and statement 2 in else can only be executed by one of two statements
        // 6. Else is directly followed by braces
    </script>

Case: leap year

  //  Algorithm: leap years are those that can be divided by 4 and can not be divided by 100 (for example, 2004 is a leap year and 1901 is not a leap year) or those that can be divided by 400 are leap years
        // Pop up the prompt input box, let the user enter the year, take this value and save it in the variable
        // Use the if statement to judge whether it is a leap year. If it is a leap year, execute the output statement in if braces, otherwise execute the output statement in else
        // Be sure to pay attention to the writing of and & & or 𞓜 in it, and pay attention to the way to judge the division is to take the remainder as 0
         var year = prompt("Please enter the year to be tested:")
        if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
            alert(year + 'It's a leap year')
        } else {
            alert(year + 'It's a normal year')
        }

two point three   if else if statement (multiple choice 1)

<script>
        // 1. Multi branch statement is the process of using multiple conditions to select different statements to get different results
        // 2. It is a multi branch statement
        // 3. Syntax specification: if else if statement
        if (Conditional expression 1) {
            //Statement 1;
        } else if (Conditional expression 2) {
            //Statement 2;
        } else if (Conditional expression 3) {
            //Statement 3;
        } else {
            //Last statement;
        }
        // 4. Implementation ideas
        // If conditional expression 1 is satisfied, execute statement 1. After execution, exit the entire if branch statement  
        // If the condition expression 1 is not satisfied, judge whether the condition expression 2 is satisfied, execute statement 2, and so on
        // If none of the above conditional expressions holds, execute the statements in else
        // 5. Precautions
        // (1) Multi branch statement or multiple choice 1. At last, only one statement can be executed
        // (2) Theoretically, there can be any number of conditions in else if
        // (3) else if there is a space in the middle
    </script>

Case: Achievements

    <script>
        //  Pseudo code is judged from large to small
        // Pop up the prompt input box, let the user enter the score, take the value and save it in the variable
        // Use the multi branch if else if statement to judge the output of different values respectively

        var score = prompt('Please enter a score:');
        if (score >= 90) {
            alert('A');
        } else if (score >= 80) {      //Don't write: 90 > score > = 80 can run the following, which must be less than 90
            alert('B');
        } else if (score >= 70) {
            alert('C');
        } else if (score >= 60) {
            alert('D');
        } else {
            alert('E');      //Use quotation marks, or you'll declare it if you think it's a variable
        }
    </script>

2.4 ternary expression

<script>
        // 1. The formula composed of ternary operators is called ternary expression
        // 2. Unary operator: + num binary operator: 3 + 5 ternary operator:?:
        // 3. Grammatical structure 
        // Conditional expression? Expression 1: expression 2
        // 4. Implementation ideas
        // If the result of the conditional expression is true, the value of expression 1 is returned. If the result of the conditional expression is false, the value of expression 2 is returned
        // 5. Code experience
        var num = 10;
        var result = num > 8 ? 'yes' : 'no' // We know that the expression has a return value and is assigned to result 
        console.log(result); //yes


        //Equivalent to:
        var num = 10;
        if (num > 5) {
            alert('yes');
        } else {
            alert('no, it isn't');
        }
        // Ternary expressions are simplified versions of if else
    </script>

Case: Digital complement 0

   <script>
        //  The user enters a number between 0 and 59
        // If the number is less than 10, fill 0 in front of this number (add 0 to splice), otherwise do not operate
        // Accept the return value with a variable and output
        var num = prompt('Please enter 0~59 A number between?')
            //Ternary expressions: expressions? Expression 1: expression 2;
        var result = num < 10 ? '0' + num : num; //The character 0 assigns the return value to a variable
        alert(result);
    </script>

2.5 switch branch process control

      The switch statement is also a multi branch statement, which is used to execute different code based on different conditions. When you want to set a series of options for a specific value for a variable, you can use switch.

    <script>
        //1. The switch statement is also a multi branch statement, and you can also select multiple 1
        // 2. Syntax structure switch conversion, switch case small examples or the meaning of options break exit
        /*     switch ((expression){
                case value1: Execute statement 1; break;
                case value2: Execute statement 2; break;
                case value3: Execute statement 3; break;
                default: Execute the last statement;
            } */
        // 3. Execution idea: use the value of our expression to match the option value behind the case. If it matches, execute the statement in the case. If it doesn't match, execute the statement in default
        switch (2) {
            case 1: alert('This is 1'); break;
            case 2: alert('This is 2'); break;  //This is 2
            case 3: alert('This is 3'); break;
            default: alert('No matching results');
        }
    </script>

matters needing attention:

        var num=1;
        switch(num){
            case 1: console.log(1);break; //1
            case 2: console.log(2);break;
            case 3: console.log(3);break;

        }
        // 1. When we develop expressions, we often write them as variables
        // 2. When the value of num matches the value in case, it is congruent. Only when the value is consistent with the data type can num === 1

3. break if there is no break in the current case, the switch will not exit, but continue to execute the next case

  var num=1;
        switch(num){
            case 1: console.log(1);//1
            case 2: console.log(2);//2
            case 3: console.log(3);//3
        }

Case: query fruit case

<script>
        //  Pop up the prompt input box, let the user enter the fruit name, take this value and save it in the variable.
        // Take this variable as the expression in switch brackets.
        // Write several different fruit names in the value after case. Be sure to put quotation marks because it must be a congruent match.
        // Just pop up different prices. Also note that break is added after each case to exit the switch statement.
        // Set default to no such fruit.
        var fruit = prompt('Please enter the fruit name')
        switch (fruit) {
            case 'Apple':
                alert('The price of apple is 3.5/Jin');
                break;
            case 'Durian':
                alert('The price of durian is 35/Jin');
                break;
            default:
                alert('No such fruit');
        }
    </script>

switch statement and if   else   If difference:

1. In general, their two statements can be replaced with each other
2. The switch... Case statement usually deals with the case where the value is determined by comparison, while the if...else... Statement is more flexible and is often used to judge the range (greater than or equal to a certain range)
3. The switch statement directly executes the conditional statement of the program after conditional judgment, which is more efficient. However, if..else statement has several conditions, you have to judge how many times.
4. When there are few branches, the execution efficiency of if...else statement is higher than that of switch statement.
five   When there are many branches, the execution efficiency of switch statement is higher and the structure is clearer.

Posted by char skd1 on Mon, 11 Oct 2021 11:23:58 -0700