Dark horse JavaScript notes ECMAScript

Posted by GinsBabu on Wed, 02 Feb 2022 02:53:26 +0100

first day

01 first acquaintance with JavaScript

1. Brief JavaScript



1.5

DOM (document object model): standard programming interface
BOM (browser object model)



Build a my JS, write alert('didi ') in the file; single quotes

2. JS notes

Single line comment: ctrl+/
Multiline comment: ctrl+shift+/

3. JS input / output statement


Alert: the output of the pop-up alert box is displayed to the user
prompt: This is an input box
Console: the console outputs to the programmer for testing

02 variable

1. Variable overview

2. Use of variables

1. Declare variables
var age;

2. Assignment
age=10;
3. Output results
console.log(age);
4. Initialization of variables
var age=10;

3. Variable syntax extension

        // 1. Update variables
        var myname = 'pink teacher';
        console.log(myname);
        myname = 'Delireba';
        console.log(myname);
        // 2. Declare multiple variables
        var age = 18,
            address = 'Huoying Village',
            gz = 2000;
        // 3. Special cases of declaring variables
        // 3.1 what is the result of only declaring no assignment? The program does not know what is stored in it, so the result is undefined
        var sex;
        console.log(sex); // undefined
        // 3.2 using a variable directly without declaration or assignment will report an error
        // console.log(tel);
        // 3.3 use of direct assignment without declaration
        qq = 110;
        console.log(qq);

4. Variable naming convention

5. Summary

03 data type

1. Introduction to data types

1. Data type of variable

        // var num; //  We are not sure which data type the num here belongs to
        var num = 10; // num is numeric 
        // The variable data type of js is determined according to the value on the right of the equal sign only when the program is running
        var str = 'pink'; // str string type
        // js is a dynamic language variable whose data type can be changed
        var x = 10; // x is numeric 
        x = 'pink'; // x string type

The variable data type of js is determined according to the value on the right of the equal sign only when the program is running
js is a dynamic language variable whose data type can be changed

2. Simple data type



**

        // Infinity
        console.log(Number.MAX_VALUE * 2); // Infinity infinity  
        // Infinitesimal
        console.log(-Number.MAX_VALUE * 2); // -Infinity infinity
        // Non numeric
        console.log('pink teacher' - 100); // NaN


3. String type string

Syntax: single quotation marks are recommended

        // 3. Detect the length of the obtained string 
        var str = 'my name is andy';
        console.log(str.length); // 15
        // 4. String splicing + as long as there is string splicing with other types, the final result is string type
        console.log('desert' + 'camel'); // String desert camel
        console.log('pink teacher' + 18); // 'teacher pink 18 '
        console.log('pink' + true); // pinktrue
        console.log(12 + 12); // 24
        console.log('12' + 12); // '1212'




3. Get variable data type


4. Data type conversion


        // 1. Convert numeric variables to string variables toString()
        var num = 10;
        var str = num.toString();
        console.log(str);
        console.log(typeof str);
        // 2. We use string (variable)   
        console.log(String(num));
        // 3. Use the method of + splicing string to realize the implicit conversion of conversion effect
        console.log(num + '');

        // var age = prompt('Please enter your age ');
        // 1. ParseInt (variable) can convert character type to number type to get integer
        // console.log(parseInt(age));
        console.log(parseInt('3.14')); // 3 rounding
        console.log(parseInt('3.94')); // 3 rounding
        console.log(parseInt('120px')); // 120 will go to this px unit
        console.log(parseInt('rem120px')); // NaN
        // 2. Parsefloat (variable) can convert character type to number type to get decimal floating point number
        console.log(parseFloat('3.14')); // 3.14
        console.log(parseFloat('120px')); // 120 will remove this px unit
        console.log(parseFloat('rem120px')); // NaN
        // 3. Use number (variable) 
        var str = '123';
        console.log(Number(str));
        console.log(Number('12'));
        // 4. Arithmetic operation - * / implicit conversion is used
        console.log('12' - 0); // 12
        console.log('123' - '120');//3
        console.log('123' * 1);//123

the second day

01JavaScript operator

1. Operator

2. Arithmetic operator




3. Increment and decrement operators





4. Comparison operator


5. Logical operator





6. Assignment operator

7. Operator priority

02JavaScript process control - Branch

1. Process control

2. Sequential process control

3. Branch process control if statement

if statement

        // 1. Syntax structure of if
        // if (conditional expression){
        //     //Execute statement
        // }

        // 2. Execution idea if the conditional expression result in if is true, execute the execution statement in braces 
        // If the result of the if conditional expression is false, the statement in braces will not be executed, and the code after the if statement will be executed
        // 3. Code experience
        if (3 < 5) {
            alert('Desert camel ');
        }

if else statement

        // 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('Get out and go home and do your homework');
        }
        // There can only be one of 1 and 2 in the final statement of else
        // 6. Else is directly followed by braces

if else if statement (multi branch statement)

        // 1. Multi branch statement is the process of using multiple conditions to select different statements and get different results
        // 2. if else if statement is a multi branch statement
        // 3. Grammatical norms
        if (Conditional expression 1) {
            // Statement 1;
        } else if (Conditional expression 2) {
            // Statement 2;
        } else if (Conditional expression 3) {
            // Statement 3;
        } else {
            // The last sentence;
        }
        // 4. Implementation ideas
        // If conditional expression 1 is satisfied, execute statement 1. After execution, exit the entire if branch statement  
        // If the conditional expression 1 is not satisfied, judge whether the conditional 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

4. Ternary expression

        // 1. The formula composed of ternary operators is called ternary expression
        // 2. ++num     3 + 5     ? :
        // 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 > 5 ? 'yes' : 'no, it isn't'; // We know that expressions have return values
        console.log(result);
        // if (num > 5) {
        //     result = 'yes';
        // } else {
        //     result = 'not';
        // }

5. Branch process control switch statement

        // 1. The switch statement is also a multi branch statement, and multiple choices can be realized
        // 2. Syntax structure: meaning of switch, switch case, small example or option
        // switch (expression){
        //     case value1:
        //         Execute statement 1;
        //         break;
        //     case value2:
        //         Execute statement 2;
        //         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
        // 4. Code verification
        switch (8) {
            case 1:
                console.log('This is 1');
                break;
            case 2:
                console.log('This is 2');
                break;
            case 3:
                console.log('This is 3');
                break;
            default:
                console.log('No matching results');

        }

        // switch precautions
        var num = 1;
        switch (num) {
            case 1:
                console.log(1);

            case 2:
                console.log(2);

            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

on the third day

01JavaScript process control - loop

1. Circulation

2. for loop

for loop syntax

        // 1. for repeatedly executes some code, which is usually related to counting
        // 2. for syntax structure
        // for (initialization variable; conditional expression; operation expression){
        //     //Circulatory body
        // }
        // 3. Initialization variable is a common variable declared with var, which is usually used as a counter 
        // 4. Conditional expression is used to determine whether each cycle continues to be executed or terminated
        // 5. The operation expression is the code executed at the end of each cycle, which is often used to update (increment or decrement) our counter variables
        // 6. Code experience: we repeatedly print 100 rounds hello
        for (var i = 1; i <= 100; i++) {
            console.log('how are you');
        }

for loop execution process

        // Execution process of for loop
        for (var i = 1; i <= 100; i++) {
            console.log('how are you');
        }
        // 1. First execute the counter variable var i = 1 But this sentence only executes index once in for
        // 2. Go to I < = 100 to judge whether the conditions are met. If the conditions are met, execute the loop body and exit the loop if the conditions are not met 
        // 3. Finally, I + + is executed. I + + is the code written separately. The first round of increment ends 
        // 4. Then execute I < = 100. If the conditions are met, execute the loop body. If the conditions are not met, exit the second round of the loop
 


Case 1

        // Pop up the input box and enter the total class number (num)
        // Enter the student's score in turn (save score), which we need to use at this time
        // for loop, the number of pop-up times is related to the total number of classes, and the conditional expression I < = num
        // Conduct business processing: calculate scores. sum first, then average
        // Pop up results
        var num = prompt('Please enter the total number of people in the class:'); // num total class size
        var sum = 0; // Summation variable
        var average = 0; // Average variable
        for (var i = 1; i <= num; i++) {
            var score = prompt('Please enter the number' + i + 'Student grades');
            // ***Because the data obtained from prompt is string type, it needs to be converted to digital type***
            sum = sum + parseFloat(score);
        }
        average = sum / num;
        alert('The total grade of the class is' + sum);
        alert('The average class score is:' + average);

3. Double for loop

Grammatical results

        // 1. Double for loop syntax structure
        // for (initialization variable of outer layer; conditional expression of outer layer; operation expression of outer layer){
        //     for (initialization variable of inner layer; conditional expression of inner layer; operation expression of inner layer){
        //         //Execute statements;
        //     }
        // }
        // 2. We can regard the inner loop as the statement of the outer loop
        // 3. The outer loop circulates once, and the inner loop executes all
        // 4. Code verification
        for (var i = 1; i <= 3; i++) {
            console.log('This is the second phase of the outer cycle' + i + 'second');
            for (var j = 1; j <= 3; j++) {
                console.log('This is the inner circle' + j + 'second');

            }
        }

Case 1: 99 multiplication table

        var a = '';
        for (var i = 1; i <= 10; i++) {
            for (var j = 1; j <= i; j++) {
                a += j + 'x' + i + '=' + j*i + '\t';
            }
            a += '\n';
        }
        console.log(a);

4. while loop

while loop syntax structure

        // 1. while loop syntax structure When
        // while (conditional expression){
        //     //Circulatory body
        // }
        // Otherwise, the execution result of the loop expression is true
        // 3. Code verification
        var num = 1;
        while (num <= 100) {
            console.log('OK, yes');
            num++;
        }
        // 4. There should also be counter initialization variables
        // 5. There should also be an operation expression to update the counter to prevent dead circulation

5. do while loop

do while syntax structure

        // 1.do while loop syntax structure
        do {
            // Circulatory body
        } while (Conditional expression)
        // 2. The execution idea is different from while in that do while executes the loop body once to judge the condition. If the result of the condition expression is true, continue to execute the loop body, otherwise exit the loop
        // 3. Code verification
        var i = 1;
        do {
            console.log('how are you?');
            i++;
        } while (i <= 100)
        // 4. Our do while loop body is executed at least once

6,continue,break

continue keyword

        // Continue keyword exit this time (current cycle) and continue to execute the remaining cycles
        for (var i = 1; i <= 5; i++) {
            if (i == 3) {
                continue; // As long as you meet continue, exit this cycle and jump directly to i++
            }
            console.log('I'm eating the third' + i + 'A steamed stuffed bun');

        }

break keyword

        // break exits the entire loop
        for (var i = 1; i <= 5; i++) {
            if (i == 3) {
                break;
            }
            console.log('I'm eating the third' + i + 'A steamed stuffed bun');

        }

02JavaScript naming conventions




the forth day

01JavaScript array

1. Concept of array

2. Create array

        // 1. Array: an elegant way to store a set of data under a single variable 
        // 2. Create an array with new
        var arr = new Array(); // An empty array was created
        // 3. Use array literal to create array []
        var arr = []; // An empty array was created
        var arr1 = [1, 2, 'pink teacher', true];
        // 4. The data in our array must be separated by commas
       // 5. The data in the array, such as 1 and 2, are called array elements

3. Gets the elements in the array

        // 6. Get array element format array name [index number] index number starts from 0 
        console.log(arr1);
        console.log(arr1[2]); // Teacher pink
        console.log(arr1[3]); // true
        var arr2 = ['Delireba', 'Gulizana', 'Tong Liya'];
        console.log(arr2[0]);
        console.log(arr2[1]);
        console.log(arr2[2]);
        console.log(arr2[3]); // Because there is no array element, the output result is undefined

4. Traversal array

        // Traversing the array: it is to access the elements of the array from beginning to end
        var arr = ['red', 'green', 'blue'];
        for (var i = 0; i < 3; i++) {
            console.log(arr[i]);
        }
        // 1. Since our array index number starts from 0, i must start from 0, i < 3
        // 2. When outputting, the ARR [i] I counter is used as an index number

5. New element in array


6. Array case

02JavaScript function

1. Concept of function

2. Use of functions


3. Parameters of function


        // 1. The function can repeat the same code
        // function cook() {
        //     console.log('hot and sour potato shreds');

        // }
        // cook();
        // cook();
        // 2. We can use the parameters of the function to repeat different codes
        // Function function name (formal parameter 1, formal parameter 2...) {/ / formal parameters (formal parameters) are in the parentheses of the declared function

        // }
        // Function name (argument 1, argument 2...)// Inside the parentheses of the function call are the arguments (actual parameters)
        // 3. Execution process of formal parameters and arguments
        function cook(aru) { // The formal parameter is the aru = 'hot and sour potato shred' parameter that accepts the argument, which is similar to a variable
            console.log(aru);

        }
        cook('sour and spicy shredded potatoes');
        cook('Big elbow');
        // 4. There can be or no parameters of the function, and the number is unlimited


4. Return value of function





Precautions for function return value

        // Precautions for function return value
        // 1. return termination function
        function getSum(num1, num2) {
            return num1 + num2; // The code after return will not be executed
            alert('I won't be executed!')
        }
        console.log(getSum(1, 2));
        // 2. return can only return one value
        function fn(num1, num2) {
            return num1, num2; // The result returned is the last value
        }
        console.log(fn(1, 2));

        // 3. We find the result of addition and subtraction multipliers of any two numbers
        function getResult(num1, num2) {
            return [num1 + num2, num1 - num2, num1 * num2, num1 / num2];
        }
        var re = getResult(1, 2); // Returns an array
        console.log(re);
        // 4. If our function has a return, it returns the value after the return. If the function does not have a return, it returns undefined
        function fun1() {
            return 666;
        }
        console.log(fun1()); // Return to 666
        function fun2() {

        }
        console.log(fun2()); // The result returned by the function is undefined


5. Use of arguments

        // The use of arguments only functions have arguments objects, and each function has built-in arguments
        function fn() {
            // console.log(arguments); //  It stores all the passed arguments arguments = [1,2,3]
            // console.log(arguments.length);
            // console.log(arguments[2]);
            // We can iterate through arguments as an array
            for (var i = 0; i < arguments.length; i++) {
                console.log(arguments[i]);

            }
        }
        fn(1, 2, 3);
        fn(1, 2, 3, 4, 5);
        // Pseudo arrays are not real arrays
        // 1. Have the length attribute of the array
        // 2. Stored by index
        // 3. It doesn't have some methods of real array, such as pop() push()

6. Function case

Case: bubble sorting

        function sort(arr){
            for(var i=0;i<arr.length-1;i++){
                for(var j=0;j<arr.length-i-1;j++){
                    if(arr[j]>arr[j+1]){
                        var a=arr[j];
                        arr[j]=arr[j+1];
                        arr[j]=a;
                    }
                }
            }
            return arr;
        }
        console.log(sort([5,4,3,2,1]));

Function can call another function

7. Two ways to declare functions


The Fifth Day

01JavaScript scope

1. Scope

        // 1.JavaScript scope: refers to the function and effect of code name (variable) in a certain range. The purpose is to improve the reliability of the program, and more importantly, to reduce naming conflicts
        // 2. Before the scope of JS (es6): global scope local scope 
        // 3. Global scope: the entire script tag or a separate js file
        var num = 10;
        var num = 30;
        console.log(num);

        // 4. Local scope (function scope) is the local scope inside the function. The name of this code only plays an effect and role inside the function
        function fn() {
            // Local scope
            var num = 20;
            console.log(num);

        }
        fn();

2. Scope of variable


       // Scope of variables: according to different scopes, our variables are divided into global variables and local variables
        // 1. Global variables: all variables in the global scope can be used in the global context
        // Note that if there is no declaration inside the function, the directly assigned variable is also a global variable
        var num = 10; // num is a global variable
        console.log(num);

        function fn() {
            console.log(num);

        }
        fn();
        // console.log(aru);

        // 2. The local variable is the variable under the local scope, and the variable inside the function is the local variable
        // Note: function parameters can also be regarded as local variables
        function fun(aru) {
            var num1 = 10; // num1 is a local variable and can only be used inside a function
            num2 = 20;
        }
        fun();
        // console.log(num1);
        // console.log(num2);
        // 3. From the perspective of execution efficiency, global variables and local variables
        // (1) Global variables are destroyed only when the browser is closed, which takes up more memory resources
        // (2) Local variables will be destroyed after the execution of our program, which saves memory resources

3. Scope chain

        Scope chain: internal functions access variables of external functions,
        The method of chain search is adopted to determine the value. This structure is called scope chain   
        Proximity principle
        var num = 10;

        function fn() { // External function
            var num = 20;

            function fun() { // Internal function
                console.log(num);

            }
            fun();
        }
        fn();//20

02JavaScript pre parsing

1. Pre analysis

2. Variable pre parsing and function pre parsing


3. Pre analysis case

        // 1 ask  
        console.log(num);

        // 2 ask
        console.log(num); // undefined Pit 1
        var num = 10;
        // It is equivalent to executing the following code
        // var num;
        // console.log(num);
        // num = 10;

        // 3 ask  
        function fn() {
            console.log(11);
        }
        fn();

        // 4 ask
        fun(); // Error reporting Pit 2 
        var fun = function() {
                console.log(22);

            }
            // Function expression calls must be written below the function expression
            // It is equivalent to executing the following code
            // var fun;
            // fun();
            // fun = function() {
            //         console.log(22);

        //     }

         1. We js Engine running js There are two steps: pre parsing code execution
         (1). Pre analysis js The engine will js Everything inside var  also function 
            Promote to the front of the current scope
         (2). Code execution is executed from top to bottom in the order of code writing
        2. Pre parsing is divided into variable pre parsing (variable promotion) and function pre parsing (function promotion)
         (1) Variable promotion is to promote all variable declarations to the front of the current scope without promoting the assignment operation
         (2) Function promotion is to promote all function declarations to the front of the current scope without calling functions

Case 4

        // Case 4
        f1();
        console.log(c);
        console.log(b);
        console.log(a);

        function f1() {
            var a = b = c = 9;
            console.log(a);
            console.log(b);
            console.log(c);
        }
        // Following code
        // function f1() {
        //     var a;
        //     a = b = c = 9;
        //     //Equivalent to var a = 9; b = 9;  c = 9;  B and C are directly assigned without var declaration. When looking at global variables
        //     //Collective declaration var a = 9, b = 9, c = 9;
        //     console.log(a);
        //     console.log(b);
        //     console.log(c);
        // }
        // f1();
        // console.log(c);
        // console.log(b);
        // console.log(a);

03JavaScript object

1. Object


2. Three ways to create objects


        // 1. Create object {} using object literal
        // var obj = {};  //  An empty object was created 
        var obj = {
                uname: 'Zhang Sanfeng',
                age: 18,
                sex: 'male',
                sayHi: function() {
                    console.log('hi~');

                }
            }
            // (1) For the attributes or methods inside, we take the form of key value pairs. Key attribute name: value attribute value 
            // (2) Multiple attributes or methods are separated by commas
            // (3) The method colon is followed by an anonymous function
            // 2. Object of use
            // (1).  We call the properties of the object and take the object name Attribute name We understand it as
        console.log(obj.uname);
        // (2).  There is also a method object name ['property name'] for calling properties
        console.log(obj['age']);
        // (3) The method sayHi object name of the calling object Do not forget to add parentheses to the method name ()
        obj.sayHi();

        // Differences among variables, attributes, functions and methods
        // 1. The similarities between variables and attributes are used to store data 
        var num = 10;
        var obj = {
            age: 18,
            fn: function() {

            }
        }

        function fn() {

        }
        console.log(obj.age);
        // console.log(age);

        // Variables are declared and assigned separately. When used, the list of variables is written directly and exists alone
        // Attributes in objects that do not need to be declared must be objects attribute
        // 2. The same point between functions and methods is to realize a certain function and do something
        // The function is declared separately and the function name () called exists separately
        // Method is called inside an object Method ()

        // Creating objects with new objects
        var obj = new Object(); // An empty object was created
        obj.uname = 'Zhang Sanfeng';
        obj.age = 18;
        obj.sex = 'male';
        obj.sayHi = function() {
                console.log('hi~');

            }
            /(1) We use the equal sign = The method of assignment adds the properties and methods of the object
            /(2) Each property and method ends with a semicolon
        console.log(obj.uname);
        console.log(obj['sex']);
        obj.sayHi();

//Why do we need to use constructors
//This is because we can only create one object at a time in the previous two methods of creating objects
//Because we create one object at a time, many of its properties and methods are the same, and we can only copy them
//So we can use the method of function to repeat the same code. We call this function constructor
//And because this function is different, it encapsulates not ordinary code, but objects
//The constructor is to abstract some of the same properties and methods in our object and encapsulate them into the function

function Person(name, age, sex) {
     this.name = name;
     this.age = age;
     this.sex = sex;
     this.sayHi = function() {
      alert('My name is:' + this.name + ',Age:' + this.age + ',Gender:' + this.sex);
    }
}
var bigbai = new Person('Big white', 100, 'male');
var smallbai = new Person('Xiaobai', 21, 'male');
console.log(bigbai.name);
console.log(smallbai.name);

        // Creating objects with constructors
        // We need to create the same attributes of the objects of the four heavenly kings: name, age, gender, the same method: singing
        // Syntax format of constructor
        // function constructor name (){
        //     this. Attribute = value;
        //     this. Method = function() {}
        // }
        // new constructor name ();
        function Star(uname, age, sex) {
            this.name = uname;
            this.age = age;
            this.sex = sex;
            this.sing = function(sang) {
                console.log(sang);

            }
        }
        var ldh = new Star('Lau Andy', 18, 'male'); // The object returned by the call is a function
        // console.log(typeof ldh);
        console.log(ldh.name);
        console.log(ldh['sex']);
        ldh.sing('Ice rain');
        var zxy = new Star('Xue You Zhang', 19, 'male');
        console.log(zxy.name);
        console.log(zxy.age);
        zxy.sing('Li Xianglan')



        // 1. The constructor name should be capitalized
        // 2. Our constructor can return the result without return
        // 3. We must use new when calling the constructor
        // 4. As long as we call the function of new Star(), we will create an object ldh {}
        // 5. We must add this before our properties and methods

3. new object

4. Traverse object properties


Day 6

01JavaScript built-in object

1. Built in object

2. Check documents

MDN

3. Math object

        / Math The mathematical object is not a constructor, so we don't need it new To call 
          Instead, you can directly use the properties and methods inside
        console.log(Math.PI); // An attribute pi
        console.log(Math.max(1, 99, 3)); // 99
        console.log(Math.max(-1, -10)); // -1
        console.log(Math.max(1, 99, 'pink teacher')); // NaN
        console.log(Math.max()); // -Infinity
        // 1. Absolute value method
        console.log(Math.abs(1)); // 1
        console.log(Math.abs(-1)); // 1
        console.log(Math.abs('-1')); // Implicit conversion converts string - 1 to numeric
        console.log(Math.abs('pink')); // NaN 

        // 2. Three rounding methods
        / (1) Math.floor()   The floor is rounded down to the minimum value
        console.log(Math.floor(1.1)); // 1
        console.log(Math.floor(1.9)); // 1
        / (2) Math.ceil()   ceil The ceiling is rounded up to the maximum value
        console.log(Math.ceil(1.1)); // 2
        console.log(Math.ceil(1.9)); // 2
        / (3) Math.round()   Rounding other numbers are rounded,
           however .5 Special, it's taken from the big one  
        console.log(Math.round(1.1)); // 1
        console.log(Math.round(1.5)); // 2
        console.log(Math.round(1.9)); // 2
        console.log(Math.round(-1.1)); // -1
        console.log(Math.round(-1.5)); // The result is - 1

        // 1.Math object random number method random() returns a random decimal 0 = < x < 1
        // 2. There are no parameters in this method
        // 3. Code verification 
        console.log(Math.random());
        // 4. We want to get a random integer between two numbers and include these two integers
        // Math.floor(Math.random() * (max - min + 1)) + min;
        function getRandom(min, max) {
            return Math.floor(Math.random() * (max - min + 1)) + min;
        }
        console.log(getRandom(1, 10));
        // 5. Random roll call  
        var arr = ['Zhang San', 'Zhang Sanfeng', 'Zhang San madman', 'Li Si', 'Li sisi', 'pink teacher'];
        // console.log(arr[0]);
        console.log(arr[getRandom(0, arr.length - 1)]);

4. Date object


        /Date() Date object is a constructor and must be used new To create our date object
        var arr = new Array(); // Create an array object
        var obj = new Object(); // An object instance was created
        / 1. use Date  If there are no parameters, return the current time of the current system
        var date = new Date();
        console.log(date);
        // 2. The commonly used writing method of parameters is numeric 2019, 10, 01 or string '2019-10-1 8:8:8'
        var date1 = new Date(2019, 10, 1);
        console.log(date1); // November is returned, not October 
        var date2 = new Date('2019-10-1 8:8:8');
        console.log(date2);

        // Format date 
        var date = new Date();
        console.log(date.getFullYear()); // Returns the year 2019 of the current date
        console.log(date.getMonth() + 1); // The month returned in the month is 1 month smaller. Remember month + 1 yo
        console.log(date.getDate()); // What number is returned
        console.log(date.getDay()); // 3 returns 1 on Monday, 6 on Saturday, and 0 on Sunday
        // Let's write a Wednesday, May 1, 2019
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var dates = date.getDate();
        var arr = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
        var day = date.getDay();
        console.log('Today is:' + year + 'year' + month + 'month' + dates + 'day ' + arr[day]);
        // Format date hour minute second
        var date = new Date();
        console.log(date.getHours()); // Time
        console.log(date.getMinutes()); // branch
        console.log(date.getSeconds()); // second
        // It is required to encapsulate a function to return the current time, minute and second format 08:08:08
        function getTimer() {
            var time = new Date();
            var h = time.getHours();
            h = h < 10 ? '0' + h : h;
            var m = time.getMinutes();
            m = m < 10 ? '0' + m : m;
            var s = time.getSeconds();
            s = s < 10 ? '0' + s : s;
            return h + ':' + m + ':' + s;
        }
        console.log(getTimer());

5. Array object



        // Add delete array element method
        // 1. push() adds one or more array elements to the end of our array
        var arr = [1, 2, 3];
        // arr.push(4, 'pink');
        console.log(arr.push(4, 'pink'));

        console.log(arr);
        // (1) push is a new element that can be added to the array
        // (2) Just write the array element directly with the push () parameter
        // (3) After the push is completed, the returned result is the length of the new array 
        // (4) The original array will also change
        // 2. unshift add one or more array elements at the beginning of our array
        console.log(arr.unshift('red', 'purple'));

        console.log(arr);
        // (1) unshift is a new element that can be appended to the front of the array
        // (2) The unshift () parameter can be written directly to the array element
        // (3) After unshift, the returned result is the length of the new array 
        // (4) The original array will also change

        // 3. pop() which can delete the last element of the array  
        console.log(arr.pop());
        console.log(arr);
        // (1) pop is the last element of the array that can be deleted. Remember that only one element can be deleted at a time
        // (2) pop() has no parameters
        // (3) After pop, the returned result is the deleted element 
        // (4) The original array will also change
        // 4. shift() which can delete the first element of the array  
        console.log(arr.shift());
        console.log(arr);
        // (1) shift is the first element of the array that can be deleted. Remember that only one element can be deleted at a time
        // (2) shift() has no parameters
        // (3) After the shift is completed, the returned result is the deleted element 
        // (4) The original array will also change

        // Array sorting
        // 1. Flip array
        var arr = ['pink', 'red', 'blue'];
        arr.reverse();
        console.log(arr);

        // 2. Array sorting (bubble sorting)
        var arr1 = [13, 4, 77, 1, 7];
        arr1.sort(function(a, b) {
            //  return a - b;  Ascending order
            return b - a; // Descending order
        });
        console.log(arr1);

        // The function of the indexof (array element) method is to return the index number of the array element and search from the front
        // Only the first index number that meets the condition is returned 
        // If it cannot find an element in the array, it returns - 1  
        // var arr = ['red', 'green', 'blue', 'pink', 'blue'];
        var arr = ['red', 'green', 'pink'];
        console.log(arr.indexOf('blue'));
        // The function of the method lastIndexOf (array element) is to return the index number of the array element and search from the back
        var arr = ['red', 'green', 'blue', 'pink', 'blue'];

        console.log(arr.lastIndexOf('blue')); // 4

        // Convert array to string 
        // 1. toString() converts our array into a string
        var arr = [1, 2, 3];
        console.log(arr.toString()); // 1,2,3
        // 2. Join (separator) 
        var arr1 = ['green', 'blue', 'pink'];
        console.log(arr1.join()); // green,blue,pink
        console.log(arr1.join('-')); // green-blue-pink
        console.log(arr1.join('&')); // green&blue&pink

6. String object




        // Returns characters based on position
        // 1. charAt(index) returns characters according to position
        var str = 'andy'; 
        console.log(str.charAt(3)); //y
        // Traverse all characters
        for (var i = 0; i < str.length; i++) {
            console.log(str.charAt(i));
        }
        // 2. charCodeAt(index) returns the character ASCII value of the corresponding index number. Purpose: to judge which key the user pressed 
        console.log(str.charCodeAt(0)); // 97
        // 3. str[index] H5 NEW
        console.log(str[0]); // a




String case

        //Given a string, such as "abaasdffggghhjjkkgfddsssss3444343", the problem is as follows: 
        // 1. Length of string 
        var str='abaasdffggghhjjkkgfddsssss3444343';
        console.log(str.length);
        // 2. Take out the characters in the specified position, such as 0, 3, 5, 9, etc 
        console.log(str.charAt(0));
        console.log(str.charAt(3));
        console.log(str.charAt(5));
        console.log(str.charAt(9));
        // 3. Find out whether the specified character exists in the above string, such as i, c, b, etc 
        console.log(str.indexOf('i'));
        console.log(str.indexOf('c'));
        console.log(str.indexOf('b'));
        // 4. Replace the specified characters, such as g with 22,ss with b and other operation methods 
        while(str.indexOf('g') !== -1){
            str=str.replace('g','22');
        }
        while(str.indexOf('ss') !== -1){
            str=str.replace('ss','b');
        }
        console.log(str);
        // 5. Intercept the string from the specified start position to the end position, for example: get the string of 1-5
        console.log(str.slice(1,5));
        // 6. Find out the character with the most occurrences and the number of occurrences in the above string 
        var str1='abaasdffggghhjjkkgfddsssss3444343';
        var o={};
        for(var i=0;i<str1.length;i++){
            var q=str1.charAt(i);
            if(o[q]){
                o[q] ++;
            }else{
                o[q]=1;
            }
        }
        console.log(o);
        //Traversal object
        var max=0;
        var ch=0;
        for(var k in o){
            if(o[k]>max){
                max=o[k];
                ch=k;
            }
            
        }
        console.log('The most frequent characters are:' + ch + 'There it is' + max + 'second');

        // 7. Traverse the string and add the symbol "@" at both ends of the traversed character

        var newStr='@';
        for(var j=0;j< str1.length; j++){
            newStr += str1.charAt(j);
        }
        newStr += '@';
        console.log(newStr);

02JavaScript simple and complex types

1. Simple and complex types


The simple data type null returns an empty object object

        // The simple data type null returns an empty object object 
        var timer = null;
        console.log(typeof timer);
        / If there is a variable that we plan to store as an object in the future,
        I haven't figured out what to put yet. I'll give it at this time null 
        // 1. Simple data types are stored in the stack. A space is directly opened in the stack to store values
        // 2. Complex data types first store the address hexadecimal representation in the stack, and then this address points to the data in the heap

2. Heap and stack

3. Simple type memory allocation

4. Memory allocation for complex types

5. Simple type parameters

6. Complex type parameters

Topics: Javascript