[Front-end JS interaction basis] Operators, process statements

1. Operators

1.1 Arithmetic operators

Arithmetic operators are used to perform mathematical operations.

Common arithmetic operators in life are: + - * / % (modulo, remainder)

// 表达式分为运算元和运算符
//JS中算术运算符:+   -    *   /   %    ++    --
// +  除字符串类型外参与的运算,执行数学运算   true隐式转换成数字 1 进行数学运算  false和null隐式转换成 0进行数学运算
console.log(10 + 20);//30
console.log(10 + 4.6);//14.6
console.log(10 + true);//11
console.log(10 + false);//10
console.log(10 + null);//10
console.log(10 + undefined);//NaN

// +  作为正号进行运算
console.log(+10);//10
console.log(+ "10");//10   可以转换数字字符串
console.log(+ "10ab");//NaN
console.log(+ true);//1
console.log(+ false);//0
console.log(+ null);//0
console.log(+ "");// 0 空字符串转为0
console.log(+ undefined);//NaN

// +  字符串参数与的多元运算,属于字符串拼接
console.log(10 + "");// "10"  "string"
console.log(10 + "10");//"1010"
console.log("10" + 10);//"1010"
console.log("10" + true);//"10true"
console.log("10" + false);//"10false"
console.log("10" + null);//"10null"
console.log("10" + undefined);//"10undefined"
console.log("10" + NaN);//"10NaN"

//  -    *   /   %     true隐式转换成数字 1 进行数学运算  false和null隐式转换成 0进行数学运算  undefined参与的都是NaN
console.log(10 - 5);//5
console.log(0.3 - 0.1);//0.19999999999999998
console.log(10 * "10");// 100 number  除了 + 之外的其它数学运算,字符串或者其它非数值类型都会隐式转为数值类型进行运算
console.log(10 * "10abc");// NaN number
console.log(10 - "");// 10
console.log(10 - false);// 10
console.log(10 / true);// 10
console.log(10 / null);// Infinity  无穷大
console.log(10 / undefined);// NaN
console.log(10 % null);// NaN

The "+" operation can be used as: addition operation, positive sign, and operations involving strings as string splicing

The above operators are also applicable to the program to perform mathematical operations. In addition to the above, there are other arithmetic operators in JS: ++(self-increment) --(self-increment)

// 前++   前--
var a = 1,
    b = a;
console.log("a:",a,"b:",b);//a: 1 b: 1

--a;// --a ===> a = a - 1
++b;// ++b ===> b = b + 1
console.log("a:",a,"b:",b);//a: 0 b: 2

a = --a;
console.log("a:",a,"b:",b);//a: -1 b: 2

var c = ++b;
console.log("a:",a,"b:",b,"c:",c);//a: -1 b: 3 c:3


// 后++   后--
var i = 1,
    j = i;
console.log("i:",i,"j:",j);//i: 1 j: 1

i--;// i--  ===> i = i - 1
j++;// j++  ===> j = j + 1
console.log("i:",i,"j:",j);//i: 0 j: 2
//总结:根据实践结果,在自身操作前++和后++  前--和后--问题上,没有什么区别

//第三方变量参与时,就不同了,如下观察结果
var s = j++;// 1. 先赋值 2. 再加加
console.log("i:",i,"j:",j,"s:",s);//i: 0 j: 3  s:2

i = i--;//这种方式只有面试的时候脑残面试官才会出这样的问题
console.log("i:",i,"j:",j,"s:",s);//i: 0 j: 3  s:2
//数学中的运算顺序:先乘除后加减
//程序中的运算同样是有顺序的:如上面的算术运算符,优先级  前++、前--、正负号(+ -) >>  *  /  % >>  + - >>  赋值运算符 = >> 后++  后--

**Exercise:** Use the prompt() method to prompt the user to enter two numbers, add the two numbers, and print the result of the sum.

​ For example: the user enters the two numbers 10 and 20, and the result after summing is 30

1.2 Comparison Operators

Comparison operators are also called relational operations.

The result of a comparison operator comparison is a Boolean value.

Comparison operators are: > < >= <= == (equal to) != (not equal to) =(all equal to) !(all not equal to)

//纯数值进行比较  按照值得大小
console.log(10 > 20);//false
console.log(3.14 == Math.PI); //false

//数值和其它基本数据类型进行比较  将其它类型转为数值类型进行运算
console.log(10 > "5");//true
console.log(10 > "10ab");//false
console.log(10 < "10ab");//false
console.log(10 == "10ab");//false
console.log(1 == true);//true
console.log(0 == false);//true
console.log(0 == null);//false
console.log(1 === true);//false 数据类型不同
// “==”比较是值是否相同,忽略了数据类型       “===”比较的是值和数据类型是否完全相同

console.log(10 >= 10);//true 等价于  判断10大于10 或者 10等于10吗?

console.log(null === null);//true
console.log(undefined === undefined);//true
console.log(NaN === NaN);//false
console.log(Infinity === Infinity);//true

console.log(null == undefined);//true  ES3中,才新增undefined数据类型,这个数据类型衍生自null  所以在比较值的时候他们是相同的
console.log(null === undefined);//false   数据类型不同  null数据类型为"object"  undefined数据类型为"undefined"

//数字字符串之间的比较  按照ASCII码从左向右逐个进行比较表进行比较  ASCII码表中 0-9 对应的 ASCII值 48-57
console.log("24" > "15");//true
console.log("10" > "5");//false
console.log("234" > "25");//false

**Exercise:** Use prompt() to prompt the user to enter two numbers, and use comparison operators to compare their values

For example: the user enters a = 150 and b = 18, then the result of a >= b comparison is true

1.3 Logical operators

Used for logical operations, the operators are: & && | || ! (logical NOT)

① Logic and &&
compare logic and to a series circuit, and imagine the process of judging as the process of current passing.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-q3ehsjE9-1687653616765) (02 operator and Math object.assets/image-20201228160908860.png)] The current passes through
: If a is true, the current can pass through to b, and the result is b; if a is false, the current cannot pass through and stay at a, and the result is a

② Logic or ||
Compare logic or to a parallel circuit, and imagine the process of judging as the process of current passing.
[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-8ddRXG2U-1687653616766) (02 operator and Math object.assets/image-20201228160957966.png)]

When the current passes: if a is true, the current directly completes the cycle from a, and the result is a; if a is false, the current cannot pass through a, but flows to b, and our result is b.

truth table

Logical AND && operation: true if both sides are true, and false if one of them is false.

a b a && b result
true true true
true false false
false true false
false false false

Logical or || operation: if one is true, it is true, and if both sides are false, the result is false

a b a || b result
true true true
true false true
false true true
false false false
//逻辑运算符:逻辑与(& &&)同时满足才满足  逻辑或(| ||)只要有一个满足即满足  逻辑非(!)
console.log(true);//true
console.log(!true);//false

console.log(10);//10
console.log(!10);//false
console.log(-10);//-10
console.log(!(-10));//false
console.log(0);//0
console.log(!0);//true
//除了0之外的所有数字,进行逻辑非操作,得结果都是 false

console.log("hello");//"hello"
console.log(!"hello");//false
console.log("");// ""
console.log(!"");//true
//非空字符串进行逻辑非操作,所得结果都是false

console.log(null);//null
console.log(!null);//true
console.log(undefined);//undefined
console.log(!undefined);//true
console.log(NaN);//NaN
console.log(!NaN);//true

// &&  和  || 具有短路效果,可以提高程序的执行效率   短路效果解释:
//逻辑与 两边同时满足才满足
//当第一个值是true的情况下,第二值决定最终结果
console.log(true &&  false);//false
console.log(true &&  true);//true
//当第一个值不成立,那么使用 && 的情况下,就不需要在进行后面的判断就能直接得出结果不满足
console.log(false &&  true);//false

//逻辑或 有一个满足即满足
//当第一个值是false的情况下,第二个值决定最终结果
console.log(false || true);//true
console.log(false || false);//false
//当第一个值条件成立,最终结果就是成立的,那么就不需要再去判断后面的结果了,这就是  || 短路效果
console.log(true || false);//true

//上面 ||  和  &&  进行运算,最终结果是 true 或 false
// 如果使用 |  和  &  进行布尔运算  最终结果是  0  或  1
console.log(true | false);//1
console.log(true & false);//0

When all basic data types perform logical operations, how to perform operations:

// 通过上一个案例逻辑非(!)的操作,我们总结出: 数值0、空字符串""、null、undefined、NaN、false都被当作条件不成立,在进行逻辑非操作时返回true
console.log(10 && 5);//5
console.log(10 && 0);//0

console.log(10 && "hello");//"hello"
console.log("" && "hello");//""

console.log("" || "10");// "10"
console.log("" || null);// null

console.log(undefined && null);// undefined

practice :

  1. false || !false && false || true;

    	false || !false && false || true
    =   false || true && false || true
    =   false || false || true
    =   false || true
    =   true
    
  2. 4 && “hello” || !false || ! true & & null ;

    	4 && "hello" || !false || !true && null;
    =   4 && "hello" || true || false && null
    =   "hello" || true || false
    =   "hello" || false
    =   "hello"
    

Added: Logical operator precedence! >> && >> ||

1.3 Assignment operator

Different from the order of operation of the previous operators from left to right, the order of operation of assignment operators is from right to left.

Such as: var num; num = 10; Assign the literal value 10 on the right to the variable num on the left

Assignment operators: = += -= *= /= %=

//声明一个变量num
var num;
console.log("num:",num);//num:undefined

//赋值运算符:=     +=    -=     *=      /=    %=
//对变量 num 进行赋值操作
num = 10;
console.log("num:",num);//num:10

num += 20;// 等价于  num = num + 20
console.log("num:",num);//num:30

num *= 10;//等价于  num = num * 10
console.log("num:",num);//num:300

num %= 7;//等价于  num = num % 7
console.log("num:",num);//num:6

num /= 3;//等价于  num = num / 3
console.log("num:",num);//num:2

1.4 Operator precedence

Operation priority: close (pre-++, pre-, positive +, negative-, logical not!) >>> Arithmetic operators (first multiplication and division, then addition and subtraction) >>> Comparison operators (first > >= < <= , then == !=)>>Logical operators (first logical and &&, then logical or ||) >>> Assignment operator >>> followed by ++, followed by –

**Order of operations: **Except for assignment operators, the order of operations is from right to left, and others are from left to right

1.5 Ternary operator

Syntax: Conditional expression? The statement to be executed if the conditional expression is true: The statement to be executed if the conditional expression is not true

Example:

var a = 100,
	b = 50;
var maxNum = a > b ? a : b;
console.log("a 与 b中的最大值是:", maxNum);//a 与 b中的最大值是: 100

Exercise: Prompt the user to enter two arbitrary integers greater than 0, and get the minimum value among them

1.6 Operator Synthesis Exercises

var a = 4;
var sum = 1 * (2 + 3) && a++ || 5 > 6 && 7 < 8 || 9;

Two, Math object

This is an object built into JS called the arithmetic object.

Math objects are used to perform mathematical tasks.

As long as it is an object, it has characteristics and behaviors, which are reflected in the program as attributes and methods.

As a built-in object in JS, the Math object has many built-in properties and methods.

Math treats itself as an object and can call these properties and methods directly.

The way the Math object calls properties and methods Math.property Math.method()

2.1 Properties of the Math object

PI Get pi Π=3.14...

2.2 Methods of the Math object

random() Get a random number between 0-1 Left closed and right open [0,1)

round(num) Get the rounded value of the parameter num

pow(x,y) Get x raised to the power of y

sqrt(num) Get the square root of the parameter num

//获取圆周率Π=3.14...
console.log(Math.PI);//3.141592653589793   JS中只能获取到小数点后15位

//pow(底数x,指数y)  获取x的y次方
console.log(Math.pow(2,4));//16

//sqrt(num)  获取开平方根
console.log(Math.sqrt(9));//3

//random()  获取 [0,1) 之间的随机数
console.log(Math.random());//每次结果不同

//获取 [0,10) 之间的随机数
console.log(Math.random() * 10);

//获取 [0,10) 之间的随机整数
console.log(parseInt(Math.random() * 10))

//获取 [0,10] 之间的随机整数
//round(num)  获取指定的四舍五入值
console.log(Math.round(Math.random() * 10))

Three, conditional statement

The conditional if statement is used to specify the statement that needs to be executed after the condition is met, and it is not executed if the condition is not met.

Similar to a selector, to select the correct answer, the condition of the question stem must be met.

There are many syntax formats for conditional statements, as follows:

  • Conditional statement with only if keyword

    if(conditional expression){

    ​ A statement that will be executed only if the conditional expression is true

    }

    Case: Determine whether a person is over 18 years old, if so, then you can enter the website to continue watching violent movies

    var age = parseInt(prompt("请输入您的年龄","18"));
    if(age >= 18){
        alert("可以观看...")
    }
    

    If the condition is met, execute the statement body in curly braces; if the condition is not met, jump out of the if statement and continue to execute the code behind the if statement.

  • There is an if statement with an else

    if(conditional expression){

    ​ A statement that will be executed only if the conditional expression is true

    }else{

    ​ The statement executed when the conditional expression is not true

    }

    Case: Determine whether a person is over 18 years old, if so, then you can enter the website to continue watching violent movies; if you are under 18 years old, please watch it accompanied by your parents.

    var age = parseInt(prompt("请输入您的年龄","18"));
    if(age >= 18){
        alert("可以观看...")
    }else{
        alert("警告!!请在家长陪同下进行观看!!")
    }
    

    Through observation, it is not difficult to find that the if...else statement can be converted with the ternary operation. The above code can be optimized with the ternary expression, as follows:

    age >= 18 ? alert("可以观看...") : alert("警告!!请在家长陪同下进行观看!!");
    
  • Multi-condition judgment statement with if else

    if (condition 1) {

    ​ Condition 1 is satisfied to execute the statement body

    }else if (condition 2){

    ​ The body of the statement that does not meet condition 1 but satisfies condition 2

    }…else if (condition N){

    ​ The body of the statement that does not meet the condition before N and satisfies the condition N

    }else{

    ​ All the above conditions are not satisfied to execute the statement

    }

    think? Assume that the employees of the company can receive corresponding welfare products according to the length of service: old employees who have reached 10 years, will receive a red envelope of 20,000 yuan, and a shopping card of 1,000 yuan; 1,000 yuan for a card; 3,000 yuan for old employees but less than 5 years old, 3,000 yuan for a red envelope, 800 yuan for a shopping card; 1,500 yuan for a shopping card for 1-year-old but less than 3 years old employees; Employees, two tickets for 300 yuan for shopping.

  • Cases where curly braces are omitted

    If there is only one statement in the curly braces of the if statement, then we can omit the curly braces.

    If there are two execution statements, if the braces are omitted, an error will be reported directly

4. Select statement

The switch statement, which is a selection statement, matches the corresponding value according to the condition, and if the match is successful, execute the statement under this match.

  • grammatical format

​ switch(expression) {

​ case value 1:

​ Sentence body 1;

​ break;

​ case value 2:

​ Sentence body 2;

​ break;

​ …

​ case value N:

​ Statement body N;

​ break;

​ default:

None of the above satisfies the executed statement body;

​ break;

​ }

Note: The default statement can be written anywhere in the switch, and it is executed when none of the case values ​​match. It is customary to put it at the end.

​ default can also be omitted. When all cases are not satisfied, no operation will be performed and the switch will directly jump out.

​ break is a control statement, which means to interrupt; it is used here to jump out of the switch statement. That is, it ends when a break statement is encountered.

Requirement 1: Please enter a number between 1-7 to determine what day of the week it is`

Requirement 2: Please enter a number between 1-12 to determine the season of the current month

  • variant

    The expression in the switch is written as true, and the conditional expression is written after the case. When the conditional expression behind the case is true, the corresponding statement body is executed, otherwise, continue to match until the match is successful, and jump out when encountering a break.

Requirement 3: According to the gender and age entered by the user, determine whether the user meets the age of marriage (male: 23, female: 20)

Fourth, the loop statement

The recurring events seen in life include: elevators in shopping malls, conveyor belts, tractor conveyor belts, machines in factories, and donkeys pulling mills.

Loop refers to the fact that as long as certain conditions are met, an action will be executed continuously. The loop will not end until the external force is passed or the condition is not met.

There are three kinds of loops in the program: while loop, do...while loop, and for loop.

4.1 do...while loop

grammatical format

​ do{

​ loop body

}while(conditional expression);

It is not difficult to find that the biggest difference between do...while and while loops is that do...while will execute the loop at least once regardless of whether the condition is true or not.

Requirements: Realize 10 "Hello World!" console output.

Exercise: Output integers between 1 and 100 that can be divisible by 3 and 7 at the same time (do...while implementation).

4.2 for loop

Grammar format:

​ for(initialization variable; conditional expression; variable operation){

​ loop body

​ }

//需求:在控制台输出 10 次"Hello World"
//while循环向for循环的演变

//初始化变量
// var i = 0;
// //while循环
// while (i < 10){//条件表达式
//     console.log("Hello World!");//大括号包裹的,叫做循环语句
//     //变量操作
//     i++;
// }

//初始化变量
// var i = 0;
// //for循环
// for (;i < 10;){//条件表达式
//     console.log("Hello World!");//大括号包裹的,叫做循环语句
//     //变量操作
//     i++;
// }

//for循环
// for (var i = 0;i < 10;){//(初始化变量; 条件表达式)
//     console.log("Hello World!");//大括号包裹的,叫做循环语句
//     //变量操作
//     i++;
// }


//for循环
for (var i = 0;i < 10; i++){//(初始化变量; 条件表达式; 变量操作)
    console.log("Hello World!");//大括号包裹的,叫做循环语句
}

4.3 Exhaustive thinking

**Overview:** We want to get a set of data, which has specific scene requirements, and the computer has no way to help us output these data. We need to manually write a program to realize this function: list all the data that may meet the requirements one by one, and then consider setting restrictions, filter out the data that meets the conditions, skip the unsatisfied data, and continue to verify A data that may meet the requirements, until all possible data are verified. This method is called the exhaustive method, and the exhaustive method is also called the full method.

​ Use the for loop to enumerate (traverse) the data that may meet the requirements;

​ Inside the for loop, use the if conditional statement to verify the potentially eligible data one by one to filter out the real eligible data.

Code demonstration: Prompt the user to input an integer greater than 0, and output all divisors of this number on the console

var num = Number(prompt("请输入一个大于 0 的整数","10"));

//按照穷举思想,先把所有可能的数据列举出来:一个数的约数,最小是1,最大是它本身
for(var i = 1; i <= num; i++){
    // console.log("i:",i);
    //按照约数的定义规则,判断是否是输出的这个数字的约数,判断条件:遍历的这个数字 i 可以整除 用户输入的数字 num
    if(num % i == 0){//取余的结果为0,即是其约数
        console.log(i,"是",num,"的约数!!");
    }
}

4.4 for loop nesting

Nested for loops, to put it bluntly, nested for loops inside for loops

The way to output data in the page document: document.write("content");

Code demonstration: output "nine-nine multiplication table" on the page

<style>
    table{
        border-collapse:collapse;
    }

    td{
        padding: 4px 8px;
        border: solid 1px;
    }
</style>
<script>
    //向页面输出内容:可以是标签也可以是文本
    // document.write("<h2>Hello World!!</h2>");

    //页面上打印 九九乘法表
    // for (var i = 1; i <= 9; i++) {//外层循环控制行
    //     for (var j = 1; j <= i ; j++) {//内层循环控制列  此时内层循环作为外层循环的循环体存在
    //         document.write(j + "&times;" + i + "=" + (i * j) + "&nbsp;&nbsp;");
    //     }
    //     //上面内层循环执行完毕后,也就相当于这一行的结束,此时在这一行后面加换行符
    //     document.write("<br>")
    // }

    //加表格
    document.write("<table>")
    for (var i = 1; i <= 9; i++) {//外层循环控制行
        document.write("<tr>")
        for (var j = 1; j <= i ; j++) {//内层循环控制列  此时内层循环作为外层循环的循环体存在
            document.write("<td>")
            document.write(j + "&times;" + i + "=" + (i * j));
            document.write("</td>")
        }
        document.write("</tr>")
    }
    document.write("</table>")
</script>

3.6 Comprehensive small exercises

Output the number of daffodils between 100 and 999 (when the number of daffodils refers to the cube sum of the values ​​on each digit is equal to the current number)

Such as 153 = 1³ + 5³ + 3³

// 穷举思想第一步:--列举出所有可能的值
for (var i = 100; i < 1000; i++) {
    // console.log("i:",i);

    //声明三个变量:接收百位数字的 b  接收十位数字的 s   接收个位数字的 g
    var b = parseInt(i / 100);
    // console.log("b:",b)
    var s = parseInt(i % 100 / 10);
    // console.log("s:",s);
    var g = parseInt(i % 10);
    // console.log("g:",g);

    //穷举思想第二步:通过设置条件,从可能的值中筛选出确定符合条件的值
    if(Math.pow(b,3) + Math.pow(s,3) + Math.pow(g,3) == i){
        console.log(i,"是水仙花数!!")
    }
}

Fourth, the control statement

Under normal circumstances, when we execute a loop, as long as the loop condition is met, the loop body will continue to execute.

At this time, we want to control the execution of the loop when a certain condition is reached during the loop, so control statements are used.

There are two control statements: break and continue

  • break Interrupt, interrupt. In JS, it can be applied to switch statement and loop statement (common in for loop) to jump out of the statement or end the execution of the statement

    Requirements: traverse the numbers between 1-10, when the number is 6, jump out of the loop; print the results: 1, 2, 3, 4, 5

    for (var i = 1; i <= 10; i++) {
        if(i == 6){
            break;
        }
        console.log("i:",i);
    }
    console.log("循环执行完毕i:",i);
    

    Console effect:

  • continue to continue. In JS, it is generally used in loop statements to skip this loop and continue to the next loop

    Requirements: traverse the numbers between 1-10, when the number is 6, skip this cycle and continue to the next cycle; print results: 1, 2, 3, 4, 5, 7, 8, 9, 10

    for (var j = 1; j <= 10; j++) {
        if(j == 6){
            continue;//跳过本次循环继续下一次循环
        }
        console.log("j:",j);
    }
    console.log("循环执行完毕j:",j);
    

    Console output effect:

  • Under multi-layer nested loops, jump out or skip the specified loop

    outter:for (var i = 1; i <= 5; i++) {
        inner:for (var j = 1; j <= 5 ; j++) {
            if(j == 3){
                // break;//跳出当前循环,当前循环为内层循环
                // continue;//跳过本次循环,继续下一次条件循环
    
                // break outter;//跳出指定标记的那一层循环
                continue outter;
            }
            console.log("i:",i,"j:",j);
        }
    }
    

    Console effect:

Guess you like

Origin blog.csdn.net/qq_39335404/article/details/131370176