I have painstakingly compiled a comprehensive collection of JavaScript knowledge points, with super detailed suggestions for collection! ! !

I have painstakingly compiled a comprehensive collection of JavaScript knowledge points, with super detailed suggestions for collection! ! !

✴️Hello everyone, I’m Mr. Wang. Mr. Wang from 3 Days and 3 Nights has sorted out the JavaScript knowledge points. The article does not have any routines, but is full of useful information.
✴️If it helps you, please give me a like so that we don’t owe each other anything.
✴️The stars are worthy of those who travel by. All luck comes from unremitting efforts. Let’s all strive together~~~

1. Syntax and variables

(1) Three layers of front-end

(2) The writing position of JS


(3) Output statements

(4) Variable declaration improvement

Variable declaration hoisting: You can use a variable declared later without throwing an exception

Before executing all code, JS has a pre-parsing phase and will pre-read the definitions of all variables.

2. Basic data types

(1) Two major types of data types in JavaScript

(2), typeof operator

The typeof operator can detect the type of a value or variable

(3) Typeof detection results of five basic data types

(4) Number type

All numbers, regardless of size, integer or floating, positive or negative, are all numeric types.


Larger numbers or smaller numbers (smaller absolute value) can be written in scientific notation

(5) Numbers in different bases

(6) A special numeric value NaN

NaN means “not a number” in English, that is, it is not a number, but it is a numerical value.

(7) String type

  • Strings are human natural language
  • The string must be wrapped in quotes, either double quotes or single quotes are acceptable.

(8) Splicing of strings

The plus sign can concatenate multiple strings


(9) Splicing of strings and variables

empty string

Sometimes you need to use an empty string, just write the closed quotation mark pair directly.

The length attribute of the string

The length attribute of a string represents the length of the string

(10) Commonly used methods for strings

(11), charAt() method

Function: Get the character at the specified position



(12), substring() method




(13), substr() method



(14), slice() method



(15) Comparison and summary of the three

(16), toUpperCase() and toLowerCase()

(17), indexOf()


(18), BOOlean (Boolean type)



(19), Undefined

The default value of an unassigned variable is undefined, and the type of undefined is also undefined, that is, undefined is both a value and a type. This type has only one value of its own.

Variable promotion situation

When a variable declaration is promoted, the value of the variable is also undefined.

(20), null type

  • The null object means empty, it is an empty object
  • When we need to destroy objects, destroy arrays or delete event listeners, we usually set them to empty.


(21) Conversion of data types

Using the Number() function


Use parseInt() function

Using parseFloat() function





(22) Introduction to complex data types


3
true
NaN
Infinity

bcd
bc
''
bc

(23), expressions and operators

Type of expression

Arithmetic, relations, logic, assignment, synthesis

(24), arithmetic operators

By default, multiplication and division have higher priority than addition and subtraction. You can use parentheses to change the order of operations if necessary.

Two functions of the plus sign


Remainder operation (modulo operation)

  • The remainder operation is also called the modulo operation and is represented by the percent sign.
  • a%b represents the remainder of a divided by b. It does not care about the integer part, only the remainder.

(25) Implicit type conversion

If an operand involved in an operation is not a number, JavaScript will automatically convert the operator to a number.


The essence of implicit conversion is to internally call the Number() function




Solution: When performing decimal operations, call the toFixed () method of the number to retain the specified decimal places.

(26), powers and roots

JavaScript does not provide power calculation or root operator, so you need to use the methods related to the Math object for calculation.

(27), rounding up and rounding down


(28), relational expressions

(29) Determine whether they are equal

(30), equal and congruent



(31), NaN is not equal to itself

How to determine if the value of a variable is NaN?

  • The isNaN() function can be used to determine whether the value of a variable is NaN.
  • But isNaN() is not easy to use. Its mechanism is: as long as the execution result of the variable passed into Number() is NaN, the isNaN() function will get true.

Not equal and not congruent

There is no consecutive comparison in JS

How should I write it to determine whether variable a is between 3 and 15?

(32), non-operation

The result of the inversion operation must be a Boolean value



(33), AND operation


(34), or operation

(35), short circuit calculation






(36) Sequence of logical operations

(37), assignment operator




(38), shortcut operators

Shortcut operators represent further operations based on the original array.

(39), auto-increment and auto-decrement operators


(40), comprehensive expression

The order of operations of comprehensive expressions: non-operation—mathematical operation—relational operation—logical operation

variable range representation

Knowledge review


function

(1) Definition and calling of functions


(2) Function call

Executing all statements in the function body is called a function call
Calling a function is very simple, just write a pair of parentheses after the function name.

(3) Execution order of statements


(4) Improvement of function declarations

Similar to variable declaration hoisting, function declarations can also be hoisted

The expression of a function cannot be promoted. If the function is defined using function expression writing, there is no promotion feature.

(5) Priority improvement of functions

<script>
        //First, the function will be promoted first
        //The variables that are defined and then promoted will not overwrite the ones that were promoted first.
        //Variable promotion will only promote the definition first and not the value.
        fun();
        var fun = function() {
            alert('A');
        }


        function fun() {
            alert('B')
        }

        fun();
    </script>

(6) Function parameters

Parameters are some specific values ​​within the function. When calling the function, the specific values ​​of these parameters must be passed in.

The function can have more or less parameters. The function can have no parameters or multiple parameters. Multiple parameters should be separated by commas.


(7) Arguments

<script>
           function fun() {
            var sum = 0;
            for (var i = 0; i < arguments.length; i++) {
                sum += arguments[i];

            }

            console.log('The sum of all parameters is:' + sum); //110
        }

        fun(33, 22, 55)
    </script>

(8) Return value of function

You can use the return keyword in the function body to indicate “the return value of the function”

//The function of the function is to return the sum of the two parameters
        function sum(a, b) {
            return a + b;
        }


        var result = sum(3, 4);
        console.log(result);

(9) Return value of function

Calling a function with a return value can be treated as an ordinary value and can appear anywhere that can be written


(10) Exit the function when encountering return

When calling a function, once a return statement is encountered, the function will immediately exit and the execution rights will be returned to the caller.

1
A
B
2

Combining if statements often does not require writing else branches.

<script>
        //Write a function. The function of the function is to determine whether a number is even.
        function checkEven(n) {
            if (n % 2 == 0) return true;
            return false;
        }

        var result = checkEven(7);
        console.log(result); //false
    </script>

Function is like a small factory

(11), exercises

<script>
        //Calculate the factorial of a number
        function factorial(n) {
            //accumulator
            var result = 1;
            for (var i = 1; i <= n; i++) {
                result *= i;

            }
            return result;
        }

        //Exhaustive method
            for (var i = 100; i <= 999; i++) {
            // Convert the number i into a string
            var i_str = i.toString();
            var a = Number(i_str[0]);
            var b = Number(i_str[1]);
            var c = Number(i_str[2]);
            //Judge based on the number of morning glory
            if (factorial(a) + factorial(b) + factorial(c) == i) {
                console.log(i);//145
            }
        }
    </script>

(12) JavaScript built-in sort() method

a and b in this function represent the front and back items in the array respectively. If they need to be swapped, a positive number will be returned, otherwise a negative number will be returned.

<script>
        var arr = [3, 5, 6, 1, 2];
        arr.sort(function(a, b) {
            return a - b;
        })

        console.log(arr);


        var arr = [99, 55, 66, 77];
        arr.sort(function(a, b) {
            return b - a;
        })

        console.log(arr);
     </script>

(13) What is recursion?

  • Statements inside a function can call the function itself, thereby initiating an iteration of the function.

  • In the new iteration, the statement calling the function itself will be executed, thus generating another iteration. When the function is executed to a certain time, no new iteration will be performed. The function is returned layer by layer, and the function is recursed.

  • Reduction is a relatively advanced programming technique that transforms a large and complex problem into a smaller problem similar to the original problem to solve.

<script>
        //Write a function and the function will call itself, thus forming recursion.
        //The function of the function is to calculate a certain factorial n. The factorial is the factorial of n*(n-1).
        function factorial(n) {
            //If you calculate the factorial of 1 at the exit of recursion, you can directly tell you the answer 1 without recursion.
            if (n == 1) return 1;
            //If the query is not the factorial of 1, return n*(n-1)!
            return n * factorial(n - 1);
        }

        var result = factorial(6);
        console.log(result); //720
    </script>

elements of recursion

  • Boundary conditions: determine when the recursion terminates, also known as the recursion exit
  • Recursive pattern: how large problems are broken down into smaller problems, also known as recursive bodies

Common recursive algorithm questions

<script>
        //Write a function. The function of this function is to return the value of the item with subscript n in the Fibonacci sequence.

        function fib(n) {
            //The values ​​of items with subscript 0 and subscript 1 in the export sequence are both 1
            if (n == 0 || n == 1) return 1;
            //The essential characteristic of the Fibonacci sequence is that each term is equal to the sum of the previous two terms.
            return fib(n - 1) + fib(n - 2);

        }
        //Write a loop statement to calculate the first 15 terms of the Fibonacci sequence
        for (var i = 0; i < 15; i++) {
            console.log(fib(i));
        }
    </script>

(14) Implement deep cloning

<script>
        //original array
        var arr1 = [33, 44, 11, 22, [77, 88],
            [11, 999]
        ];
        //Result array "each has a result"
        var result = [];
        //Function This function will be recursive

        function deepClone(arr) {
            //Iterate through each item of the array
            for (var i = 0; i < arr.length; i++) {
                //Type judgment if the item traversed is an array
                if (Array.isArray(arr[i])) {
                    //recursion
                    result.push(deepClone(arr[i]));
                } else {
                    //If the item traversed is not an array but a basic type, it is pushed directly into the result array.
                    //Equivalent to the recursive exit
                    result.push(arr[i])

                }
            }
            //return result array
            return result;

        }
        //have a test
        var arr2 = deepClone(arr1);
        console.log(arr2);

        //Whether the lotus roots are broken or not?
        console.log(arr1[4] == arr2[4]);
        arr1[4].push(99);
        console.log(arr1)
        console.log(arr2);
    </script>

How to implement deep cloning?

Using the idea of ​​recursion, the overall idea is similar to shallow cloning, but with some changes. If the traversed item is a basic type value, it is directly pushed into the result array. If the traversed item is an array, the shallow cloning process is repeated. operate.

(15), shallow cloning

<script>
        //Prepare the original array
        var arr1 = [33, 44, 55, 66, [99, 22], 111];
        //Prepare a result array
        var result = [];
        //Traverse the original array
        for (var i = 0; i < arr1.length; i++) {
            result.push(arr1[i]);
        }
        //output result array
        console.log(result);
        // Test whether cloning is implemented, which means it is essentially a different array in memory.
        console.log(arr1 == result); // false
        //Testing that such a clone is a shallow clone is "broken and connected"
        arr1[4].push(100);
        console.log(result);
    </script>

(16) Global variables and local variables

variable scope

JavaScript is a function-scoped programming language: variables only have meaning within the function in which they are defined.

global variables

If the function is not defined inside any function, the variable is a global variable. It can be accessed and changed within any function

(17). Masking effect

Masking effect: If a variable with the same name as the global one is also defined in the function, the variables in the function will mask the global variable.

(18). Consider the situation of variable improvement


(19) Formal parameters are also local variables

<script>
        var a = 10;

        function fun(a) {
            a++;
            console.log(a); //8
        }

        fun(7);
        console.log(a); //10
    </script>

(20), scope chain

A function can also be defined inside a function. Similar to local variables, a function defined inside a function is a local function.


Scope chain: In function nesting, variables will search for their definitions layer by layer from the inside to the outside.

<script>
        var a = 10;
        var b = 20;

        function fun() {
            var c = 30;

            function inner() {
                var a = 40;
                var d = 50;
                console.log(a, b, c, d); //40 20 30 50
            }
            inner();
        }

        fun();
    </script>

Without var, global variables will be defined

When assigning a value to a variable for the first time, if var is not added, a global variable will be defined.

<script>
        var a = 1;
        var b = 2;

        function fun() {
            //The letter c does not add the var keyword, so it is a global variable
            c = 3;
            var b = 4;
            b++;
            c++;
        }
        fun();
        console.log(b); //2
        //Variable c can be accessed outside the function
        console.log(c); //4
    </script>

(21), closure


What is a closure: A closure is a combination of the function itself and the environmental state in which the function is declared. A function can “remember” the environment in which it is defined and can access it even if the function is not called in the environment in which it is defined. The environment variable in which it was defined

<script>
        //Create a function
        function fun() {
            //Define local variables
            var name = 'MOOC';
            //Return a local function
            return function() {
                alert(name)
            }
        }

        //Call the external function to get the internal function
        var inner = fun();
        //Define a global variable
        var name = 'ABC';
        //Executing the inn function is equivalent to executing the internal function outside the fun function
        inner()
    </script>

Observe the phenomenon of closure

In JavaScript, a closure is created every time a function is created
However, closures often require the function to be executed in another place before it can be observed.

The purpose of closure

  • Memorability: When a closure is generated, the state of the environment in which the function is located will always remain in the memory and will not be automatically cleared after the outer function is called. This is the memorability of the closure.
<script>
        function createCheckTemp(standardTemp) {
            function checkTemp(n) {
                if (n <= standardTemp) {
                    alert("Your temperature is normal")
                } else {
                    alert("Your body temperature is high")
                }
            }
            return checkTemp;
        }
        //Create a checkTemp function, which takes 37.1 as the standard line
        var checkTemp_A = createCheckTemp(37.1);
        //Create a checkTemp function, which takes 37.3 as the standard line
        var checkTemp_B = createCheckTemp(37.3);

        checkTemp_A(37.2);
        checkTemp_B(37.2);
    </script>

The purpose of closures—simulating private variables

<script>
        //Encapsulate a variable. The function of this function is to privatize the variable.
        function fun() {
            //Define a local variable a
            var a = 0;
            return {
                getA: function() {
                    return a;
                },
                add: function() {
                    a++;
                },
                pow: function() {
                    a *= 2;
                }
            }
        }
        var obj = fun();
        //If you want to use variable a outside the fun function, the only way is to call the getA() method
        console.log(obj.getA());
        //I want a to add one operation
        obj.add();
        console.log(obj.getA());
        obj.pow();
        console.log(obj.getA());
    </script>

Notes on using closures

Closures cannot be abused, otherwise it will cause performance problems on the web page, and in severe cases, it may lead to memory leaks. The so-called memory leak means that the dynamically allocated memory in the program is not released or cannot be released for some reason.

<script>
        function addCount() {
            var count = 0;
            return function() {
                count = count + 1;
                console.log(count);
            }
        }

        var fun1 = addCount();
        var fun2 = addCount();
        fun1(); //1
        fun2(); //1
        fun2(); //2
        fun1(); //2
    </script>

(22), IIFE

IIFE (Immediately Invoked Function Expression) is a special way of writing JavaScript functions. Once defined, it is called immediately.

Methods of forming IIFE

Functions cannot be called directly with parentheses

Functions must be converted into function expressions before they can be called

The role of IIFE

Assigning values ​​to variables: When assigning values ​​to variables requires some more complex calculations (such as if statements), using IIFE appears to have a more compact syntax.


IIFE can change global variables into local variables in some situations (such as for loops) and the syntax is more compact.

(41), flow control statement

Basic use of if statement




//requires three digits
        var n = Number(prompt('Please enter three digits'));
        //Perform legal verification on the value entered by the user
        if (!isNaN(n) && 100 <= n && n <= 999) {
            var a = parseInt(n / 100);
            var b = parseInt(n / 10) % 10;
            var c = n % 10;
            if (Math.pow(a, 3) + Math.pow(b, 3) + Math.pow(c, 3)) {
                alert('is the number of daffodils');
            }
        } else {
            alert('The number you entered is illegal')
        }

(42), switch statement

The purpose of the switch statement: when a variable is classified and discussed


The switch statement is not like the if statement, which will automatically jump out of the if statement after executing a certain branch. We must actively call the break statement to jump out of the break statement body. If break is not written, all subsequent cases will be regarded as matching. Until I meet break

<script>
        //Let the user enter the month
        var month = Number(prompt('Please enter the month'));
        //Classification discussion
        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                alert('This month has 31 days');
                break;

            case 4:
            case 6:
            case 9:
            case 11:
                alert('This month has 28 days');
                break;

            case 2:
                alert('This month has 28 or 29 days');
                break;
            default:
                alert('The month you entered is incorrect')

        }
    </script>

(43), ternary operator

The purpose of the ternary operator: select the value of a variable between two different values ​​depending on whether a certain condition is true.

(44), for loop

Execution mechanism of for loop statement


Accurately traverse for loop





<script>
        //sum is the initial value of the accumulator is 0
        for (var i = 1, sum = 0; i <= 100; i++) {
            sum += i;
        }
        console.log(sum); //5050
    </script>

//Exhaustive method
        for (var i = 1; i < 100; i++) {
            if (i % 3 == 1 && i % 4 == 2 && i % 5 == 3) {
                console.log(i); //58
            }
        }

(45), while loop statement

  • The while statement is also a loop statement. It is a loop with an indefinite range. It has different uses than the for loop. Almost all loops provide both for loops and while loops.

  • The while statement does not specify the start and end range of the loop in advance. As long as the test conditions are met, the loop will be executed.

  • The while loop does not explicitly define the loop variable. You must first define the loop variable outside the while loop. Sometimes there is even no loop variable.

  • The statements in the loop body must make the loop test condition tend to be invalid, otherwise an infinite loop will occur.

var i = 1;
        while (i <= 100) {
            console.log(i);
            i++;
        }
//Find the smallest integer such that the sum of squares of n is greater than 456789
        //Exhaustive method starts testing from 1
        var n = 1;
        while (n * n < 456789) {
            n++;
        }

        console.log(n); //676

var n = 1;
        var sum = 0;
        while (sum < 500) {
            sum += n;
            n++;
        }
        //Note that there is an "error" here
        console.log(n - 1); //32

(46), break and continue

break means to terminate the loop immediately. It can only be used in loop statements and can be used in both for loops and while loops.


continue is used to skip one iteration in the loop and continue executing the next iteration in the loop. continue is often used in for loops.

(47), do while statement


<script>
        //A form of post-judgment executes the loop body at least once
        do {
            console.log('★');
        } while (false); //★
    </script>
var n = 1;
        do {
            console.log(n);
            n++
        } while (n <= 100);

(48), random number function

Random number function gets decimal between 0 and 1

(49), do while small case

<script>
        do {
            var dx = parseInt(Math.random() * 9) - 4;
            var dy = parseInt(Math.random() * 9) - 4;
        }
        while (dx == 0 && dy == 0);
        console.log(dx, dy);
    </script>

(Fifty), guessing number games

<script>
        //Random number 2-99
        var answer = parseInt(Math.random() * 98) + 2;
        //The maximum and minimum values ​​of the range at this time are used to prompt the user.
        var min = 1;
        var max = 100;
        //Continuous repetition uses an infinite loop
        while (true) {
            //Ask the user to guess the number
            var n = Number(prompt('Please guess the number' + min + '~' + max));
            //Verify whether the number entered by the user is within the range
            if (n <= min || n >= max) {
                alert('The number you entered is not within the range')
                    //Abandon this loop and start the next iteration
                continue;
            }
            //Determine the relationship between the number entered by the user and the answer
            if (n > answer) {
                alert('The number you entered is too large');
                //Because the number entered by the user is larger, the maximum range of numbers at this time can be changed to the value entered by the user.
                max = n;
            } else if (n < answer) {
                alert('The number you entered is too small')
                    //Because the number entered by the user is smaller, the minimum range of numbers at this time can be changed to the value entered by the user.
                min = n;


            } else {
                alert('guessed correctly');
                //End the infinite loop
                break;
            }
        }
    </script>

(51) What is an algorithm?

  • An algorithm refers to an accurate and complete description of a problem-solving solution, a series of clear instructions for solving a problem. An algorithm represents a systematic method to describe a strategic mechanism for solving a problem. That is to say, it is able to perform certain standardized inputs within a limited time. Get the requested output

  • An algorithm is to break down a problem into steps that a computer can execute step by step.

Requirements for excellent algorithms

  • correctness
  • Robustness
  • readability

(52), pseudo code

(53) How to cultivate algorithms

  • Knock more, practice more, summarize more
  • Classic business demand scenarios should be kept in mind

(54), Accumulator


//User enters number n
        var n = Number(prompt('Please enter a number'));

        //accumulator
        var sum = 0;
        //Iterate through the denominator
        for (var i = 2; i <= n; i++) {
            sum += (i + 1) / i
        }

        alert(sum.toFixed(2));

(55), Accumulator

<script>
        //Calculate factorial
        var n = Number(prompt('Please enter a number'));
        //The accumulator starts from 1. If you want to start from 0, any number multiplied by 0 will be 0.
        var result = 1;
        //Traverse backwards to calculate factorial
        for (var i = n; i >= 1; i--) {
            result *= i;
        }

        alert(result);
    </script>

(56), exhaustive method

The most outstanding ability of a computer is calculation. It does not have the ability to summarize or reason logically. Therefore, when people use computers to solve problems, they should make full use of their strengths and avoid weaknesses and give full play to the advantages of computers instead of asking them to perform logical reasoning. The exhaustive method is like this. an algorithmic idea.

What is the exhaustive method?

The exhaustive method, as the name suggests, refers to determining the approximate range of the answer based on the conditions of the question, and verifying all possible situations one by one within this range until all situations are verified. If a certain situation meets the conditions of the question, it is the question. If all the conditions are not met after verification, then there is no solution to this problem.

//Exhaustive method
        for (var i = 1; i <= 100; i++) {
            if (i % 3 == 0 && i % 5 == 0) {
                console.log(i);
            }
        }
//Find the divisor
        var n = Number(prompt('Please enter a number:'));
        //Exhaustive method
        for (var i = 1; i <= n; i++) {
            if (n % i == 0) {
                console.log(i);
            }
        }
//Find the number of daffodils
        for (var i = 100; i < 1000; i++) {
            var i_str = i.toString();
            var a = i_str.charAt(0);
            var b = i_str.charAt(1);
            var c = i_str.charAt(2);
            if (Math.pow(a, 3) + Math.pow(b, 3) + Math.pow(c, 3) == i) {
                console.log(i);
            }
        }

(23), Introduction to DOM


(24) Commonly used attributes of nodeType

(25), access element nodes

The so-called accessing element nodes refers to getting, getting the element nodes on the page.

To perform any operation on a node, you need to obtain the node. Accessing the node mainly relies on the document object.

Understanding the document object

(26) Commonly used methods to access element nodes

(27), getElementById ()

  • If there are elements with the same id on the page, you can only get the first one
  • No matter how deep the element is hidden, it can be found through the Id.

delayed run


(28), getElementsByTagName()

Precautions:

  • Arrays are convenient for traversal, so element nodes can be manipulated in batches
  • Even if there is only one node with the specified tag name on the page, an array of length 1 is obtained.
  • Any node element can also call the getElementsByTagName() method to obtain an internal element node of a certain class.

(Twenty-nine), getElementsByClassName()



(30), querySelector()



(31), querySelectorAll()


(31), node relationship



Text nodes are also nodes
In the standard W3C specification, empty text nodes should also be counted as nodes, but there will also be certain compatibility issues in IE8 and previous nodes. They do not regard empty text nodes as nodes.

(32), node operation

Changing the content in an element node can use two related properties

The innerHTML attribute can set the content in the node in HTML syntax

The innerText property can only set the content in the node in the form of plain text

(33) How to change the CSS style of element nodes

(34) How to change the HTML attributes of element nodes

(35) Creation of nodes


appendChild()

insertBefore()

<body>
    <div id="box">
        <p>I am the original paragraph 0</p>
        <p>I am the original paragraph 1</p>
        <p>I am the original paragraph 2</p>
    </div>
    <script>
        var oBox = document.getElementById('box');
        var oPs = oBox.getElementsByTagName('p');

        //Create orphan node
        var oP = document.createElement('p');
        //Set internal text
        oP.innerHTML = 'I'm new here'
            //Up the tree
            //oBox.appendChild(oP);
        oBox.insertBefore(oP, oPs[0])
    </script>
</body>

(36), mobile node

(37), delete node



(38), clone node


(39), event monitoring

What is an event: user interaction with a web page

For example: when the user clicks on an element, when the mouse moves over the element, when the content of the text box is changed, when the keyboard is pressed in the text box, when the web page is loaded…

What is event listening?

Listening, as the name suggests, allows the computer to detect that this event has occurred and execute some programs pre-written by the programmer.


<style>
        div {
            width: 200px;
            height: 200px;
            background-color: #ccc;
        }
    </style>
</head>

<body>
    <div id="box">

    </div>
    <script>
        var oBox = document.getElementById('box');
        //Add a click event listener to this box
        oBox.onclick = function() {
            alert('Hello, I am the function of the click event');
        }
    </script>

(40) Common mouse event monitoring


(41) Common keyboard events


(42) Common form event monitoring

(39), event monitoring

What is an event: user interaction with a web page

For example: when the user clicks on an element, when the mouse moves over the element, when the content of the text box is changed, when the keyboard is pressed in the text box, when the web page is loaded…

What is event listening?

Listening, as the name suggests, allows the computer to detect that this event has occurred and execute some programs pre-written by the programmer.


<style>
        div {
            width: 200px;
            height: 200px;
            background-color: #ccc;
        }
    </style>
</head>

<body>
    <div id="box">

    </div>
    <script>
        var oBox = document.getElementById('box');
        //Add a click event listener to this box
        oBox.onclick = function() {
            alert('Hello, I am the function of the click event');
        }
    </script>

(40) Common mouse event monitoring


(41) Common keyboard events


(42) Common form event monitoring

(45) Common page monitoring events

(46), event propagation


<script>
        var box1 = document.getElementById("box1");
        var box2 = document.getElementById("box2");
        var box3 = document.getElementById("box3");
        //   box1.onclick = function() {
        //       alert('A');
        //   }
        //   box1.onclick = function() {
        //       alert('B '); //B
        //   }


        box2.addEventListener("click", function() {
            alert('C ');
        }, false)

        box2.addEventListener("click", function() {
            alert('D '); //First C then D
        }, false)
    </script>

(47), event object

The event processing function provides a formal parameter, which is an object that encapsulates the details of this event. This parameter is usually represented by the word event or the letter e.

(48), mouse position



<style>
        * {
            margin: 0;
            padding: 0;
        }
        
        #box {
            width: 200px;
            height: 200px;
            background-color: #333;
            margin: 100px;
            padding: 50px;
        }
        
        body {
            height: 2000px;
        }
        
        #info {
            font-size: 30px;
        }
    </style>
</head>

<body>
    <div id="box">

    </div>
    <div id="info">

    </div>
    <script>
        var oBox = document.getElementById('box');

        var oInfo = document.getElementById('info');

        oBox.onmouseover = function(e) {
            oInfo.innerHTML = 'offsetX / Y: ' +
                e.offsetX + ',' + e.offsetY + '<br/>' + 'clientX/Y:' + e.clientX + ',' + e.clientY;

        }
    </script>

(49), character code

key code

<script>
        var oList = document.getElementById('list');

        var lis = oList.getElementsByTagName('li');

        //Write loop statements to add monitors in batches
        for (var i = 0; i < lis.length; i++) {
            lis[i].onclick = function() {
                this.style.color = ' red';
            }
        }
    </script>

Performance issues when adding event listeners in batches

Each event listener registration will consume a certain amount of system memory, and adding events in batches will result in too many listeners and very large memory consumption.

In fact, each li’s event handling function is a different function, and these functions themselves will also occupy memory.

(50), event delegation

Utilize the event bubbling mechanism to delegate events from descendant elements to ancestor elements



<button id="btn">Create a new list item by me</button>
    <ul id="list">
        <li>list item</li>
        <li>list item</li>
        <li>list item</li>
    </ul>
    <script>
        var oList = document.getElementById('list');
        var oBtn = document.getElementById('btn')
        oList.onclick = function(e) {
            //e.target represents the element that the user actually clicked on
            e.target.style.color = 'red';
            // e.currentTarget represents the entire list item
            // e.currentTarget.style.color = 'blue';


        }

        oBtn.onclick = function() {
            //Create a new li element
            var oLi = document.createElement('li');
            //write content
            oLi.innerText = 'I'm new here';
            //Up the tree
            oList.appendChild(oLi);
        }
    </script>


(51), timers and delays

function parameters

Named functions can also be passed in setInterval

What is a named function? What is an anonymous function?

Named function, so the name means a function with a name. Named functions are generally the most commonly defined ones.

// function
function fn() {
    console.log('I am a named function')
    console.log('Look, I have a name')
    console.log('My name is fn')
}
fn()
fn()

anonymous function

We can also see functions without names and anonymous functions everywhere. Let’s write a few anonymous functions.

setTimeout(function () {
  console.log('I am an anonymous function, I am used for timer parameter passing')
}, 1000)

let arr = [1, 2, 3]
arr.forEach(function (item) {
  console.log('I am an anonymous function and I am used as a callback function parameter')
})

let box = document.querySelector('#box')
box.onclick = function () {
  console.log('I am an anonymous function, I am used to bind events')
}

(52) Clear timer

<h1 id="info"></h1>
    <button id="btn1">start</button>
    <button id="btn2">pause</button>
    <script>
        var oInfo = document.getElementById('info')
        var btn1 = document.getElementById("btn1");
        var btn2 = document.getElementById("btn2");

        var a = 0;
        //Set a global variable
        var timer;

        btn1.onclick = function() {
            //In order to prevent the timer from overlapping, we should clear the timer before setting the timer.
            clearInterval(timer)
                //Change the value of the global variable to a timer entity
            timer = setInterval(function() {
                oInfo.innerText = ++a;
            }, 1000)
        }

        btn2.onclick = function() {
            clearInterval(timer)
        }
    </script>

Delay


<button id="btn1">Hello pops up after 2 seconds</button>
    <button id="btn2">Cancel popup after 2 seconds</button>
    <script>
        var btn1 = document.getElementById("btn1");
        var btn2 = document.getElementById("btn2");

        var timer;
        btn1.onclick = function() {
            timer = setTimeout(function() {
                alert('Hello, world!');
            }, 2000)
        }

        btn2.onclick = function() {
            clearInterval(timer);
        }
    </script>

(53), first understanding of asynchronous functions


(53) What is BOM?

  • The Window object is the window in which the current JS script is running, and this window contains the DOM object. The window.document property is the document object.
  • In the browser function with tabs, each tab has its own window object. That is to say, tabs in the same window will not share a window object.

Global variables are properties of window


The above results mean that multiple JS files share scopes, that is, JS files do not have scope isolation function.

Built-in functions are generally window methods

(54) Properties related to window size


(55), resize event


(56), scrolled height


(57), scroll event


(58), Navigator object


(59), History object

A common operation is to simulate the browser’s back button

(60), Location object

Reload current page



(61), BOM special effects development return to top

<!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>
    <style>
        body {
            height: 5000px;
            background-image: linear-gradient(to bottom, blue, green, yellow);
        }
        
        .backtotop {
            width: 60px;
            height: 60px;
            background-color: rgba(255, 255, 255, 0.6);
            position: fixed;
            bottom: 100px;
            right: 100px;
            cursor: pointer;
        }
    </style>
</head>

<body>
    <div class="backtotop" id="backtotopbtn">Back to top</div>
    <script>
        var backtotopbtn = document.getElementById("backtotopbtn");
        var timer;
        backtotopbtn.onclick = function() {
            //Set the table to close first
            clearInterval(timer);
            //Set the timer
            timer = setInterval(function() {
                //Let scrollTop continue to decrease
                document.documentElement.scrollTop -= 80;
                // timer stops
                if (document.documentElement.scrollTop <= 10) {
                    clearInterval(timer);
                }
            }, 20)
        }
    </script>
</body>

</html>

object-oriented

(62), understanding objects

An object is a collection of key-value pairs, representing the mapping relationship between attributes and values.

(63), object syntax


Property access

The value of a specified key in an object can be accessed using “dot syntax”

If the attribute does not conform to the naming convention of JS identifiers, it must be accessed using square brackets.


If the attribute name is stored in the form of a variable, it must be in the form of square brackets

Changes to properties

You can change an attribute by directly using the assignment operator to reassign a value to an attribute.

Creation of attributes

If the object itself does not have a certain attribute value, the attribute will be created when assigning using dot syntax.

Deletion of attributes

If you want to delete the attributes of an object, you need to use the delete operator


(64), object methods

If a property value is a function, it is also called a method of the object

Method calling: Use dot syntax to call methods of an object

methods and functions

Methods and functions, but the method is the function attribute of the object, it needs to be called using the object

Object traversal

Similar to traversing an array, objects can also be traversed. To traverse an object, you need to use a for…in… loop. To use a for…in loop, you need to be able to traverse a certain key of the object.

(65), values ​​of basic types and reference types

Object is a reference type value

Objects are reference type values, which means:



<script>
        var obj1 = {
            a: 1,
            b: 2,
            c: [33, 44, {
                m: 55,
                n: 66,
                p: [77, 88]
            }]
        };
        //Implement deep cloning
        function deepClone(o) {
            //To determine whether o is an object or an array
            if (Array.isArray(o)) {
                //array
                var result = [];
                for (var i = 0; i < o.length; i++) {
                    result.push(deepClone(o[i]))
                }
            } else if (typeof o == "object") {
                //object
                var result = {};
                for (var k in o) {
                    //Original value after recursion
                    result[k] = deepClone(o[k]);
                }

            } else {
                //Basic type value
                var result = o;

            }
            return result;
        }

        var obj2 = deepClone(obj1);
        console.log(obj2);

        //See if there is any disconnection.
        //The values ​​of reference types are not equal to each other
        console.log(obj1.c == obj2.c); //false
        obj1.c.push(99);
        console.log(obj2); //obj2 remains unchanged because there is no disconnection.
        obj1.c[2].p.push(99);
        console.log(obj1);
    </script>

(66) Understanding the context

What is context?


function context

  • The this keyword can be used in functions, which represents the context of the function

  • Similar to this in Chinese, what this in a function specifically refers to must be judged by the preface and suffix when calling the function.

this in the function




As can be seen from the above, the context of a function is determined by the way the function is called. That is to say, if the same function is called in different forms, the context of the function will be different.

The above two examples:

Scenario 1: Object management calls a function, this in the function refers to the managed object


Scenario 2: Parentheses call the function directly, and this in the function refers to the window object.

Let’s take a case

What do the two thiss in this question refer to: I don’t know! ! Because the context of a function can only be determined when it is called, the context of a function cannot be determined.

Output 3

Output NaN




Examples of questions in Rule 1 – Question 1

Examples of questions in Rule 1 – Question 2


Examples of questions in Rule 1 – Question 3


Rule 2

Rule 2: If the function is called directly by parentheses, the context of the function is the window object.

Rule 2 – Question 1


Rule 2 – Question 2


Context rule three

Rule 3: The array (array-like object) enumerates the function and calls it, and the context is this array (array-like object)

Rule 3 – Question 1


What is an array-like object?

All objects whose key names are natural number sequences (starting from 0) and have a length attribute

The arguments object is the most common array-like object, which is the actual parameter list of the function.

Rule 3 Question 1

Rule 4

IIFE function, the context is the window object



Rule five

Rule 5: Timer and delayer call functions, the context is the window object


Output: 7

Context Rule 6

Rule 6: The context of the event handling function is the DOM element to which the event is bound.

Practice small demo


(67), call and apply can specify the context of the function


(68), the difference between call and apply


Should I use call or apply?

(69), summary of context rules

(70). Use the new operator to call functions

JS stipulates that using the new operator to call a function will proceed in four steps:

  • A blank object will be automatically created within the function body.
  • The context of the function (this) will point to this object
  • The statements within the function body will be executed
  • The function will return the context object itself, even if the function has no return statement

(71), constructor

What is a constructor?

  • Call a function with new. This function is called a constructor. Any function can be a constructor. You just need to call it with new.
  • As the name suggests, the constructor is used to construct a new object. The statements inside it will add several properties and methods to the new object to complete the initialization of the object.
  • The constructor must be called using the new keyword, otherwise it will not work properly. Therefore, developers agree that the first letter of the constructor name should be capitalized.



If you don’t call the constructor with new

this in the constructor is not the function itself

Try adding methods to objects


(72), classes and instances



Constructors and classes

  • Java, C++, etc. are “object-oriented” languages

  • JavaScript is an “object-based language”

  • The constructor in JavaScript can be compared to the class in OO language. The writing method is indeed similar, but it is still fundamentally different from the real OO language.

(Seventy-three), prototype and prototype chain search

What is a prototype?

  • Any function has a prototype attribute, prototype means “prototype”
  • The prototype property value is an object, which by default has a constructor property pointing back to the function



Prototype chain lookup



(Seventy-four), hasOwnProperty method

(seventy-five), in

The in operator can only check whether a property or method can be accessed by the object, but cannot check whether it is its own property or method.



The end of the prototype chain


About the prototype chain of arrays


(Seventy-six), inheritance

Two unrelated classes

The relationship between People and Students

  • The People class has the same properties and methods as the Student class, and the Student class also extends some properties and methods.
  • Student is a kind of People, and the relationship between the two categories is “is a kind of”
  • This is the inheritance relationship. The Student class inherits the People class
  • Inheritance describes the relationship between two classes. For example, a student is a kind of person, so there is an inheritance relationship between humans and students.
    – People is the “parent class” (“super class”, “base class”); Student is the “subclass” (or derived class)

More examples of inheritance relationships

(Seventy-seven), How to implement inheritance in JavaScript

The key to realizing inheritance is that the subclass must have all the attributes and methods of the parent class, and it should also be able to define its own unique attributes and methods. It is a common practice to use the unique prototype chain feature to implement inheritance.

Inheritance through prototype chain



(Seventy-eight), what exactly is object-oriented?

  • The essence of object-oriented: define different classes and let instances of the classes work

  • Advantages of object-oriented: Program writing is clearer, code structure is more rigorous, making the code more robust and easier to maintain

  • Object-oriented is often used in situations where encapsulation and reusability are required (component thinking)

(Seventy-nine), packaging



Summary of packaging knowledge points


The purpose of a wrapper class is to allow basic type values ​​to obtain methods from the prototype of their constructor

(80) Methods of Math object




(81), Date() date object


Timestamp

  • The timestamp represents the number of milliseconds from zero o’clock on January 1, 1970 to a certain moment.
  • The date object can be turned into a timestamp through the getTime() method or the Date.parse() function.
  • By writing new Date (timestamp), the timestamp can be turned into a date object

(82) Summary of regular expression knowledge points

1. What is a regular expression?

  • Regular expression, also called regular expression, is an expression composed of ordinary characters and special characters.
  • Its function is to check whether the string meets the format requirements, or to find whether there is a string in the string that meets the format requirements.

2. How to create a regular expression

  • Use the constructor method to create:var regular expression name = new RegExp('regular expression content', 'modifier');
  • Create using literal form:var regular expression name =/regular expression content/modifier;

3. Commonly used methods of regular expressions—test method

  • Function: Verify whether the string meets the format requirements of the regular expression

  • Format:Regular expression.test(string)

  • Return value: true (meets the requirements), false (does not meet the requirements)


4. The composition of regular expressions

(1) Ordinary characters

  • Such as letters, numbers 0-9, az, AZ, _

(2) Special characters (metacharacters)

(1), locator

^: means starting with a certain character, such as /^a/ means the string starts with the letter a

$: means ending with a certain character, such as /$a/ means the string ends with a




(2), qualifier indicating quantity

  • *:It means that the number of characters in front of it is from 0 to infinite. For example, /a*/ means that the number of a is at least 0 and at most infinite.

  • +: Indicates that the number of characters in front of it is from 1 to infinite. For example, /a+/ means that the number of a is at least 1 and at most unlimited.

  • ?: means that the characters before it are 0 to 1. For example, /a?/ means that the number of a’s is at least 0 and at most one.

  • {n}: means that the characters in front of it can only be n. For example, /a{3}/ means that the string contains 3 characters a

  • {n, }: means that the number of characters in front of it is from n to infinite. For example, /a{3, }/ means that the number of string a is greater than or equal to 3.

  • {n,m}: indicates that the number of characters in front of it is nm. For example, a{1,5} indicates that the number of a is 1-5.

(3), escape characters

Escape character: The so-called escape character refers to adding a backslash in front of an ordinary character to make it have specific functions and meanings. You can also add a backslash in front of a character with specific functions and meanings to convert it into Ordinary characters such as: \d represents any number/\ represents converting the slash in the regular expression into an ordinary slash

  • \d: represents any number

  • \D: represents any non-number

  • \w: represents any letter, number, or underscore

  • \W: Any non-alphanumeric underscore

  • \s: represents any whitespace character, such as tab or space

  • \S: Any non-whitespace character

(4), alternative character set

  • [value 1 value 2 value 3 value 4]: The value inside the square brackets represents any value that can be matched in the string.

  • [value1-valuen]:Indicates that any value between value 1 and value n is an alternative option

  • [^value1 value2 value3]: Indicates that the string cannot contain any value in the square brackets

  • [\u4e00-\9fa5]: represents any Chinese character

4. Regular expression matching patterns
1) Greedy mode: refers to the regular expression matching as many characters as possible when matching strings. The default is greedy mode.

2) Lazy mode: refers to the regular expression matching as few characters as possible when matching strings. The default is greedy mode. If you want to convert greedy mode into lazy mode, you need to add a question mark after the quantity modifier.


(5) Methods used in conjunction with regular expressions in string objects

(1), split method

  • Function: Convert string to array
  • Format:String name.splite('separator');

(2), match method

  • Function: Find matching conditions from a string
  • Format: string.match(substring);
  • Return value: an array formed by substrings. By default, only the first substring found that meets the conditions is returned. If you want to find all substrings that meet the conditions, you need to use regular expressions as parameters.



(3) Repalce method

  • Function: Replace the specified substring in the string

  • Format:String.repalce.('substring to be replaced','new substring');

  • Return value: By default, only the first substring that meets the conditions is replaced. If you want to replace all substrings, you need to use a regular expression and this regular expression needs to use the modifier g. If you want to replace the substring If the string does not exist, return the original string.

(4) Search method

  • Function: Search the substring position from left to right in the string. If it exists, return the subscript corresponding to the substring. Otherwise, return -1. The function is similar toindexOfmethod
  • Format:String.search('substring');
  • Note: This method can be used in conjunction with regular expressions, but even if there is a modifier g in the regular expression, it can only return the first substring found when matching.

6. Commonly used modifiers of regular expressions

  • i: indicates ignoring case
  • g: indicates global matching
  • ig/gi: means ignoring case and matching globally


Related Posts

Node.js implements WebSocket

HTML rotating photo album (0 basics, learn in 1 minute)

Teach you step by step how to make the navigation bar at the bottom of your mobile phone, and your boss will agree after reading it

[Ajax] HTTP related issues-GET-POST-XHR usage-ajax in jQuery-cross-domain-same origin-jsonp-cors

Front-end knowledge – flex layout of css

Introduction and use of Normalize.css

Introduction to asynchronous request ajax, native ajax, basic use of $.ajax

8 detailed implementation methods for css centering

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*