Complete collection of JavaScript knowledge points - siege lion from Anyang normal school to share!!!

Introduction: JavaScript is the programming language of web

  1. In web, HTML defines the content of web pages, css describes the layout of web pages, and JavaScript controls the behavior of web pages. At the same time, JavaScript can be used for HTML and web, and can be widely used in servers, PC s, laptops, tablets, smartphones and other devices.
  2. JavaScript is a scripting language, a lightweight programming language, which can insert the programming code of html pages and can be executed by all modern browsers
  3. JavaScript: write directly to the html output stream document Write ("< H1 > this is a title < / H1 >"); Document. Can only be used in html output Write, if this method is used after the document is loaded, the whole document will be overwritten

JavaScript usage:

  1. JavaScript scripts are located between and can be placed in the body and head parts of html pages
  2. The browser interprets and executes the JavaScript code in the middle of the script tag
  3. JavaScript functions and events
    <!DOCTYPE html>
    function myFunction()
        document.getElementById("demo").innerHTML="My first JavaScript function";
    <h1>my Web page</h1>
    <p id="demo">A paragraph</p>
    <button type="button" onclick="myFunction()">Try it</button>
  1. Fill in the onclick event in the label. When calling a function, the format is onclick = function name + ()
  2. Use document. In html output stream Write is equivalent to adding a string of html code to the original html code. If you use it after the document is loaded (such as using a function), the entire document will be overwritten.

JavaScript output: JS doesn't have any function to print or output, but JS can display data in a different way

  1. Use window Alert() pop up warning box
  2. Use document The write () method writes the content to the html document
  3. Use innerHMTL to write to html elements
  4. Use console Log() is written to the console of the browser and the JavaScript value is displayed in the browser.
  5. document.getElementById("demo") is JavaScript code that uses the id attribute to find HTML elements
  6. InnerHTML = "paragraph modified." Is JavaScript code used to modify the HTML content of an element (innerHTML).
  7. Please use document Write () simply outputs what is written to the document. If you execute document. After the document has finished loading Write, the entire HTML page will be overwritten.

js syntax: scripting language, lightweight but powerful programming language

  1. Literal quantity of JS: in programming language, generally fixed value is called literal quantity

  2. A number literal can be an integer or decimal, or a scientific count (e)

  3. A string literal can use single or double quotation marks

  4. Express literal quantity for calculation: 5 + 3

  5. Array literal defines an array: [40, 100, 1, 5, 25, 10]

  6. The object literal defines an object: {firstName: "John", lastName: "Doe", age:50, eyeColor: "blue"}

  7. Function literal defines a function: function myfunction (a, b) {return a * B;}

  8. JS variable: in the programming language, variables are used to store data values. JS uses VaR to define variables and uses = to assign var x = 5 to variables. Variables can be accessed through variable names. In an imperative language, variables are usually variable. Literal is a constant value. Note: a variable is a name and a literal is a value

  9. JS operator:
    1. Assignment, arithmetic and bitwise operators: =, +, -, *, / are described in js operator.
    2. Condition, comparison and logical operators, = =,! = < > Described in js comparison operator

  10. JS has many data types: number, string, array, object and so on
    var length = 16; // Number is assigned by numeric literal
    var points = x * 10; // Number is assigned by expression literal
    var lastName = “Johnson”; // String assignment by string literal
    var cars = [“Saab”, “Volvo”, “BMW”]; // Array is assigned by array literal
    var person = {firstName:“John”, lastName:“Doe”}; // Object is assigned by object literal

  11. js function: js statements can be written in functions, and functions can be referenced repeatedly. Reference a function = call a function (execute the statement in the function).

  12. js character case: js is case sensitive,

  13. js uses the Unicode character set, which covers all characters, including the punctuation character deng

  14. In JavaScript, the naming rules of hump method are common, such as lastName (not lastname).

  15. Javascript code is a sequence of JavaScript statements, and the browser executes each statement in turn according to the writing order.

  16. JavaScript code block, which starts with the left curly bracket and ends with the right curly bracket. The function of a code block is to execute a sequence of statements together.

JS statement identifier:

  1. break is used to jump out of a loop
  2. Catch statement block, which executes catch statement when there is an error in the execution of try statement
  3. continue jumps out of the iteration in the loop
  4. Do while executes a statement block and continues to execute the statement block when the conditional statement is true
  5. for when the conditional statement is true, the code block can be executed a specified number of times
  6. for - in is used to traverse the properties of an array or object (loop the array or object properties)
  7. Function defines a function
  8. If else is used to perform different actions under basically different conditions
  9. return exit function
  10. switch is used to perform different actions based on different conditions
  11. Throw throw throw error
  12. try implements error handling and is used with catch
  13. var declares a variable
  14. while executes the statement block when the conditional statement is true
    Note: JavaScript is a scripting language. The browser will execute the script code line by line when reading the code. For traditional programming, all code will be compiled before execution.

JS variables are regarded as containers for storing data.

  1. Variables must start with letters,
  2. Variables can also be expressed as $and_ Start with a symbol (but we don't recommend this)
  3. Variable names are case sensitive (Y and y are different variables)
  4. Both JavaScript statements and JavaScript variables are case sensitive.

Data type of JS:

  1. JS variables can also hold other data types, such as text values and numeric values
  2. When assigning a text value to a variable, the value should be enclosed in double or single quotes
  3. When assigning a value to a variable, do not use quotation marks. If quotation marks are used to surround the value, the value will be treated as text

Detailed explanation of JS data types

  1. Value type (basic type): String, number, Boolean, Null, Undefined, Symbol(Symbol is a new raw data type introduced by ES6 to represent unique values).
  2. Reference data types: object, array, function.
  3. JS has dynamic types, which means that the same variables can be used as different types
  4. JS string: a string is a variable that stores characters (such as "Bill Gates"). A string can be any text in quotation marks. You can use single or double quotation marks:
  5. JS Boolean (logical) values can only have two values: true or false
  6. JS array: var cars=new Array("Saab", "Volvo", "BMW"); or var cars=[“Saab”,“Volvo”,“BMW”];
    Array subscripts are zero based, so the first entry is [0], the second is [1], and so on.
  7. JS objects are separated by curly braces. Inside the parentheses, the attributes of the object are defined in the form of name and value pairs (Name: value). Attributes are separated by commas:
    var person={firstname:"John", lastname:"Doe", id:5566};
  8. When the variable is declared as null, the value of the variable can be set to null. When the variable is declared as null, the value of the variable can be set to null

JS object: it has the data of attributes and methods. The object is also a variable, but the object can contain multiple values (multiple variables), and each value is rendered in a name:value pair.

  1. JS objects can be understood as containers of variables (key value pairs and methods). Key value pairs are usually written as name: value (keys and values are separated by colons). Key value pairs are usually called object attributes in JS objects
  2. Characters can be used to define and create JS objects: var person = {firstName: "John", lastName: "Doe", age:50, eyeColor: "blue"};
  3. The method of the object defines a function and is stored as the attribute of the object. The object method is called (as a function) by adding ().
  4. Fullname() method of person object: name = person fullName();
  5. If you want to access the fullname attribute of the person object, it will be returned as a string defining the function, name = person fullName;
    // create object
    methodName : function() {
        // code 
    //Use the following syntax to access object methods
    //Usually fullName() is a method as a person object and fullName is a property.
    // If the fullName attribute is used, without adding (), it will return the definition of the function:

JS functions are reusable blocks of code that are event driven or executed when it is called

    <!DOCTYPE html>
    <meta charset="utf-8">
    <title>Test example</title>
    function myFunction()
        alert("Hello World!");
    <button onclick="myFunction()">Point me</button>
  1. JS function is a code block wrapped in curly braces, preceded by the keyword function
  2. function functionname() {/ / execute code}. When the function is called, the code in the function will be executed,
  3. Functions can be called directly when an event occurs (such as when the user clicks a button), and can be called by JavaScript anywhere.
  4. JavaScript is case sensitive. The keyword function must be lowercase and the function must be called in the same case as the function name.
  5. When calling a function, you can pass values to it, that is, parameters. These parameters can be used in the function. You can send multiple parameters separated by commas
  6. When declaring a function, the parameters are declared as variables. Variables and parameters must appear in the same order. The first variable is the given value of the first parameter passed
  7. The function with return value returns the specified value by using return. At the same time, the function stops, but the whole JS code will not stop. At the same time, the function call will be replaced by the return value,
  8. Local JS variable: the variable declared inside the JS function (using var) is a local variable, which can only be accessed inside the function. The scope of the variable is local. Local variables with the same name can be used in different functions, because only the function that has declared the variable can recognize the variable. As long as the function runs, the local variable will be deleted.
  9. The variable declared outside the function is a global variable, which can be accessed by all scripts and functions on the web page
  10. The life cycle of JS variables starts from the time they are declared. Local variables will be deleted after the function runs, and global variables will be deleted after the page is closed
  11. If you assign a value to a variable that has not been declared, the variable will be automatically used as an attribute of window
  12. Your global variable or function can override the variable or function of the window object.
    Local variables, including window objects, can override global variables and functions.

JS event details

  1. html events are events that occur on html elements. JS can trigger these events when using JS on html pages
  2. html events can be browser behavior or user behavior, such as html page loading, click event, etc. when the event is triggered, JS can execute the predetermined code,
  3. Common html events:
    onchange:html element changes
    onclick: the user clicks on the html element
    onmouseover: user moves mouse over html element
    onmouseout: the user moves the mouse away from the html element
    onkeydown: the user presses the keyboard key
    onload: the browser finishes loading the page

JS string explanation

  1. JS string is used to store and process text. The string can be any character inserted into quotation marks, but quotation marks or double quotation marks can be used
  2. You can use the index to access each character in the string from 0. You can use quotation marks in the string. The quotation marks in the string should not be the same as those in the string:
  3. Use the built-in attribute length to calculate the length of the string
  4. JS string is the original value. You can use the string to create var firstName = "John"
  5. Use the new keyword to define a string as an object: var firstName = new String("John")
  6. Don't create a String object. It will slow down execution and have other side effects
  7. Original value strings, such as "John", have no properties and methods (because they are not objects)
  8. The original value can use JavaScript properties and methods, because JS can treat the original value as an object when executing methods and properties.
  9. String attribute: constructor: returns the function that creates the string attribute. Length returns the string length. prototype allows you to add attributes and methods to the object

String method:

  1. charAt() returns the character at the specified index position
  2. indexOf() returns the position in the string where the specified character first appears
  3. split() splits a string into an array of substrings
  4. toString() returns the value of a string object
  5. valueOf() returns the original value of a string object

Typeof, null, undefined in JS

  1. typeof operator: detects the data type of the variable
    typeof "John" / / string returned
    typeof 3.14 / / number is returned
    typeof false / / boolean is returned
    typeof [1,2,3,4] / / return object
    typeof {name: 'John', age:34} / / object returned
    Array is a special object type. Therefore, typeof [1,2,3,4] returns object.
  2. Null: it means nothing. Null is a special type with only one value, which represents a reference to an empty object. Use typeof to detect null and return object.
  3. Undefined: in JS, undefined is a variable with no set value, and typeof a variable with no value will return undefined.
    var person; // The value is undefined (empty), and the type is undefined
  4. Difference between undefined and null: null and undefined have equal values but different types:
  typeof undefined             // undefined
   typeof null                  // object
   null === undefined           // false
   null == undefined            // true

JS data type summary

  1. JS has six different data types: string, number, Boolean, obkect, function and symbol
  2. Js has three object types: Object,Date and Array
  3. JS has two data types that do not contain any values: null and undefined
    typeof "John"                 // Return string
    typeof 3.14                   // Return number
    typeof NaN                    // Return number
    typeof false                  // Return boolean
    typeof [1,2,3,4]              // Return object
    typeof {name:'John', age:34}  // Return object
    typeof new Date()             // Return object
    typeof function () {}         // Return function
    typeof myCar                  // Return undefined (if myCar does not declare)
    typeof null                   // Return object
    NaN The data type is number
    array(Array)The data type is object
    date(Date)The data type of is object
    null The data type is object
    The data type of the undefined variable is undefined
    If the object is JavaScript Array or JavaScript Date ,We can't pass typeof To determine their type, because they are all returned object. 

The constructor property of JS returns the constructors of all JS variables

    "John".constructor                 // Return function string() {[native code]}
    (3.14).constructor                 // Return function number() {[native code]}
    false.constructor                  // Return function boolean() {[native code]}
    [1,2,3,4].constructor              // Return function array() {[native code]}
    {name:'John', age:34}.constructor  // Return function object() {[native code]}
    new Date().constructor             // Return function date() {[native code]}
    function () {}.constructor         // Return function () {[native code]}

JS regular expressions use a single string to describe and match a series of string search patterns that conform to a certain syntactic rule.

  1. A regular expression is a search pattern formed by a sequence of characters. When you search for data in text, you can use search patterns to describe what you want to query.
  2. A regular expression can be a simple character or a more complex pattern. Regular expressions can be used for all text search and text replacement operations.
  3. Regular expression syntax: / regular expression body / modifier (optional)
  4. Example: var patt = /runoob/i, runoob is a regular expression body (for retrieval). i is a modifier (search is not case sensitive).

Using string method: in JS, a regular expression is usually used for two string methods: search() and replace().

  1. The search method is used to retrieve the starting substring or substring in the regular expression, and returns the substring that matches the specified substring in the search method.
  2. The replace() method is used to replace some characters with others in a string, or to replace a substring that matches a regular expression.

Regular expression modifiers: modifiers can be case insensitive in global search:

  1. i performs case insensitive matching. 0
  2. g perform a global match (find all matches instead of stopping after the first match is found).
  3. m performs multiline matching.

Regular expression pattern:

  1. Square brackets are used to find characters in a range:
    [abc] find any character between square brackets.
    [0-9] find any number from 0 to 9.
    (x|y) find any options separated by |.
  2. Metacharacters are characters with special meanings:
    \d find numbers.
    \s find white space characters.
    \b match word boundaries.
    \uxxxx looks up Unicode characters specified by the hexadecimal number xxxx.
  3. classifier:
    N + matches any string that contains at least one n.
    N * matches any string containing zero or more n's.
    n? Matches any string containing zero or one n.
    Regular expression form validation instance:
    /*With decimal*/
    function    isDecimal(strValue )  {  
       var  objRegExp= /^\d+\.\d+$/;
       return  objRegExp.test(strValue);  
    /*Check whether the Chinese name is composed */
    function ischina(str) {
        var reg=/^[\u4E00-\u9FA5]{2,4}$/;   /*Define validation expression*/
        return reg.test(str);     /*Verify*/
    /*Check whether it is all composed of 8 digits */
    function isStudentNo(str) {
        var reg=/^[0-9]{8}$/;   /*Define validation expression*/
        return reg.test(str);     /*Verify*/
    /*Verify phone code format */
    function isTelCode(str) {
        var reg= /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/;
        return reg.test(str);
    /*Check whether the email address is legal */
    function IsEmail(str) {
        var reg=/^\w+@[a-zA-Z0-9]{2,10}(?:\.[a-z]{2,4}){1,3}$/;
        return reg.test(str);

JS error - throw, try and catch

  1. The try statement tests for errors in the code block,
  2. catch statement processing error
  3. throw statementcreate custom error
  4. finally statement after the try and catch statements, the statement will be executed whether there is a trigger exception or not

JS error: various errors may occur when the JS engine executes JS code

  1. Syntax errors, usually coding errors or typos caused by programmers.
  2. Misspelling or missing features in the language (possibly due to browser differences).
  3. An error caused by incorrect output from a server or user.
  4. It may also be due to many other unpredictable factors.

JS throws a throw error: when an error occurs, when something goes wrong, the JavaScript engine usually stops and generates an error message. The technical term for this is that JavaScript will throw an error.

JavaScript try and catch try statements allow us to define blocks of code that are tested for errors at execution time. The catch statement allows us to define the code block to be executed when an error occurs in the try code block.
Try {... / / exception throw} catch(e) {... / / exception capture and processing} finally {... / / end processing} finally statement this code block will be executed regardless of whether an exception is generated in the previous try and catch.
The throw statement allows us to create custom errors. The correct technical term is to create or throw an exception. If throw is used with try and catch, you can control the program flow and generate custom error messages. Syntax: throw exception

JS statement promotion:

  1. In JS, the declaration of functions and variables will be promoted to the top of functions. Functions can be declared after use, that is, variables can be used first and then declared
    x = 5; // The variable x is set to 5
    elem = document.getElementById("demo"); // Find element
    elem.innerHTML = x;                     // Show x in element
    var x; // Declaration x
  1. Declaration promotion: function declarations and variable declarations are always promoted to the top of the method body by the interpreter

  2. JS initialization will not be promoted, only declared variables will be promoted, and initialization will not

  3. JS reserved keywords: in JS, some identifiers are reserved keywords and cannot be used as variable names or function names, such as if, VaR, this and in

  4. You should avoid using the names of JavaScript built-in objects, properties and methods as variables or function names of javascript:

  5. JavaScript is often used with Java. You should avoid using some Java objects and attributes as JavaScript identifiers:

  6. In addition to retaining keywords, there are also some non-standard keywords in JavaScript implementation. One example is the const keyword, which is used to define variables.

  7. Some JavaScript engines use const as a synonym for var. Other engines treat const as a definition of a read-only variable.

JS this keyword:

  1. An object-oriented language, this represents a reference to the current object, but this is not fixed in JS. It will change with the change of execution environment.
  2. In the method category, this represents the object to which the method belongs
  3. Used alone, this represents the global object [object Window]:
  4. In the function, this represents the global object
  5. In function type, in strict mode, this is undefined.
  6. In an event, this represents the element that receives the event.
  7. Methods like call() and apply() can reference this to any object.

(ES6) added two important JavaScript Keywords: let and const.

  1. The variables declared by let are only valid in the code block where the let command is located
  2. const declares a read-only constant. Once declared, the value of the constant cannot be changed.
  3. Before ES6, JavaScript had only two scopes: global variables and local variables within functions.
  4. Variables declared with var in the function can only be accessed in the function content. If var is not used, it is a global variable.
  5. Variables declared with var keyword do not have the characteristics of block level scope, and they can still be accessed outside {}.
  6. Before ES6, there was no concept of block level scope. ES6 can use let keyword to implement block level scope
  7. The variables declared by let are only valid in the code block {} where the let command is located, and cannot be accessed outside {}.
  8. Redefining variables using var key children can also cause problems
    var x = 10;
    // Here, the output x is 10
        var x = 2;
        // Here, the output x is 2
    // Here, the output x is 2

JSON of JS is used to store and transmit data format. JSON is usually used to transfer data from the server to the web page

  1. JSON, the full English name of JavaScript Object Notation, is a lightweight two-point data exchange format and an independent language
  2. JSON uses JavaScript syntax, but the JSON format is just a text.
    Text can be read by any programming language and transmitted as data format.

JSON instance:
{"sites":[ {"name":"Runoob", "url":""}, {"name":"Google", "url":""}, {"name":"Taobao", "url":""} ]}
3. JSON is formatted as JS object, that is, JS program can easily convert JSON data into JS object
4. JSON data is a key value pair, separated by commas. Curly braces retain objects and square brackets retain arrays
5. JSON data: a name corresponds to a value. The key / value pair includes the field name (in double quotation marks), followed by a colon, followed by the value: "name": "Runoob"
6. JSON objects are stored in braces: objects can store multiple key value pairs: {name ":" Runoob "," url ":" "}
7. The JSON array is kept in square brackets, and the array can contain objects

        {"name":"Runoob", "url":""}, 
        {"name":"Google", "url":""},
        {"name":"Taobao", "url":""}

Convert JSON string to JS object: usually, we heap JSON data from the server and display the data on the web page,

establish JS character string:String is JSON Format data, and then use JS Built in function JSON.parse()Convert string to JS Object, and then we can use it in the page JSON I've got your data
    var text = '{ "sites" : [' +
    '{ "name":"Runoob" , "url":"" },' +
    '{ "name":"Google" , "url":"" },' +
    '{ "name":"Taobao" , "url":"" } ]}';
    obj = JSON.parse(text);
    document.getElementById("demo").innerHTML = obj.sites[1].name + " " + obj.sites[1].url;
  1. JSON.parse() is used to convert a JSON string into a JS object
  2. JSON.stringify() is used to convert JS values to JSON strings

javascript:void(0) meaning

  1. Javascript: the key word in void (0) is the void keyword. Void is a very important keyword in JavaScript. This operator specifies to evaluate an expression but does not return a value.
  2. Syntax format:
    void func()
    javascript:void func()

  1. Differences between href = "#" and href="javascript:void(0)"
  2. It contains a location information. The default anchor is #top, which is the upper end of the web page. javascript:void(0) only represents a dead link.

  3. When the page is very long, you will use # to locate the specific location of the page. The format is: # + id.
  4. If you want to define a dead link, use javascript:void(0).
  5. void() simply means that no value is returned, but the expression in parentheses still needs to be run, such as

JS asynchronous programming

  1. Asynchronous (async) is a concept opposite to synchronous (sync).
  2. In traditional single thread programming, the program runs synchronously. (synchronization does not mean that all steps run at the same time, but that the steps are executed in sequence in a control flow sequence).
  3. The concept of asynchrony does not guarantee synchronization, that is, the execution of an asynchronous process will no longer have a sequential relationship with the original sequence.
  4. Synchronous execution is in the order of your code, asynchronous execution is not in the order of your code, and asynchronous execution is more efficient.

[the external chain picture transfer fails. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-Mj1kObkM-1620288964476)(:/e4fcb0406dbc4b788d16246bc3ae3f15)]

When to use asynchronous programming?

  1. In front-end programming (even in the back-end sometimes), when we deal with some short and fast operations, such as calculating the result of 1 + 1, we can often complete it in the main thread. As a thread, the main thread cannot accept multiple requests at the same time. Therefore, when an event does not end, the interface will not be able to process other requests.
  2. Now there is a button. If we set its onclick event as an endless loop, when this button is pressed, the whole web page will lose response. In order to avoid this situation, we often use sub threads to complete things that may take long enough to be noticed by users, such as reading a large file or making a network request. Because the child thread is independent of the main thread, even if it is blocked, it will not affect the operation of the main thread.
  3. The sub thread has one limitation: once it is launched, it will lose synchronization with the main thread. We can't determine its end. If we need to deal with some things after the end, such as processing information from the server, we can't merge it into the main thread.
  4. In order to solve this problem, asynchronous operation functions in JavaScript often realize the result processing of asynchronous tasks through callback functions.

Callback function: it is a function that tells it when we start an asynchronous task: what to do after you finish the task. In this way, the main thread hardly cares about the state of the asynchronous task, and it will start and end well by itself.

    function print() {
    setTimeout(print, 3000);
    In this program setTimeout It is a process that takes a long time (3 seconds). Its first parameter is a callback function and the second parameter is the number of milliseconds. After the function is executed, a sub thread will be generated. The sub thread will wait for 3 seconds and then execute the callback function "print",Output on command line "Time out". 

Asynchronous AJAX; In addition to the setTimeout function, asynchronous callbacks are widely used in AJAX programming.

JS Promise

  1. Promise is a class provided by ES6, which aims to write complex asynchronous tasks more gracefully.
  2. Therefore, some old browsers do not support ES6. Only browsers above Safari 10 of apple and Edge 14 of Windows began to support ES6 features.
    Promise Syntax:
    new Promise(function (resolve, reject) {
        // What to do

For example, if I want to output a string in three times, the first interval is 1 second, the second interval is 4 seconds, and the third interval is 3 seconds:

    Code example 1: complete the above functions
        setTimeout(function () {
            setTimeout(function () {
                setTimeout(function () {
                }, 3000);
            }, 4000);
        }, 1000);
    1. This program realizes this function, but it uses "Function waterfall" To achieve. It is conceivable that in a complex program,
    2. use "Function waterfall" Whether the maintenance or exception handling of the implemented program is a particularly cumbersome thing, and it will make the indentation format very redundant.
Code example 2: complete the above functions
    new Promise(function (resolve, reject) {
    setTimeout(function () {
        }, 1000);
    }).then(function () {
        return new Promise(function (resolve, reject) {
            setTimeout(function () {
            }, 4000);
    }).then(function () {
        setTimeout(function () {
        }, 3000);

Promise usage:

  1. Promise constructor has only one parameter and is a function. This function will be run asynchronously after construction, so we call it the starting function
  2. The starting function contains two parameters: resolve and reject. When promise is constructed, the initial function will be executed asynchronously;
    Example 1:
    ew Promise(function (resolve, reject) {
        console.log("Run"); Program direct output Run 
    resolve and reject Functions are called. resolve It means everything is normal, reject Is called when an exception occurs:
    Example 2:
    new Promise(function (resolve, reject) {
        var a = 0;
        var b = 1;
        if (b == 0) reject("Divide zero");
        else resolve(a / b);
    }).then(function (value) {
        console.log("a / b = " + value);
    }).catch(function (err) {
    }).finally(function () {
    The result of program execution is a / b = 0 End
    Promise Class has .then() .catch() and .finally() Three methods
    .then() You can add functions in parameters to the current Promise Normal execution sequence of,
    .catch() Is the setting Promise Exception handling sequence,
    finally() Yes Promise The sequence that must be executed at the end of execution.
    .then() The incoming functions will be executed in sequence, and any exceptions will jump directly to the catch Sequence:
    Example 3:
    new Promise(function (resolve, reject) {
    }).then(function (value) {
        return 3333;
    }).then(function (value) {
        throw "An error";
    }).catch(function (err) {
    Execution result: 111122223333 An error
    resolve() You can place a parameter in the for the next then Pass a value
    then Functions in can also return a value passed to then
    But if then Returned in is a Promise Object, then next then Will be equivalent to the return of this Promise Operate
    reject() An exception is usually passed in the parameter to the subsequent catch The function is used to handle exceptions.
    be careful:
    resolve and reject The scope of is only the starting function, excluding then And other sequences;
    resolve and reject It doesn't stop the starting function, don't forget return. 
  1. The then, catch and finally sequences can be transformed, but it is best to write the program in the then catch finally order.
  2. In addition to the then block, the other two blocks can be used multiple times. Finally, they will be executed in sequence like then, but the catch block will only execute the first one, unless there is an exception in the catch block. So it's best to arrange only one catch and finally block.
  3. By default, then blocks will be executed in downward order. return cannot be interrupted. You can jump to catch through throw to interrupt.

When is it appropriate to use Promise instead of traditional callback functions?

  1. When asynchronous operations need to be performed several times in sequence, for example, if you want to detect the user name and password successively through asynchronous methods, Promise is suitable when you need to detect the user name asynchronously and then the password asynchronously.
  2. Promise is just a better programming style. Not at all. It's a way to convert asynchrony to synchronization

JS code specification

  1. Hump naming method is used for variable names
  2. Usually, you need to add a space before and after the operator (= + - * /):
  3. Usually use 4 space symbols to indent the code block: it is not recommended to use TAB key to indent, because the resolution of TAB key is different in different editors.
  4. A statement usually ends with a semicolon.
  5. Place the left curly bracket at the end of the first line. Add a space before the left curly bracket. Place the right curly bracket on a separate line. Don't end a complex statement with a semicolon.
    Naming rules:
    1. Variables and functions are identified by the small hump method, that is, except the first word, other words are capitalized (lowerCamelCase)
  6. The global variable is UPPERCASE
  7. Constants (such as PI) are capitalized (UPPERCASE)

JS function definition:

  1. JS uses function to define functions. Korean can be defined by declaration or an expression
  2. function myFunction(a, b) { return a * b; }
  3. Semicolons are used to isolate executable JS statements. Since the function declaration is not an executable statement, it does not end with semicolons
  4. JS functions can be defined through expressions: after the function expression stores variables, variables can also be used as a function
     var x = function (a, b) {return a * b};
     var z = x(4, 3); 
     The above function ends with a semicolon because it is an execution statement.
  1. The above functions are actually anonymous functions (functions have no name). Functions are stored in variables and do not need function names. Usually called by using a variable name

Function() constructor: the function can also be defined through the built-in JS function constructor

    var myFunction = new Function("a", "b", "return a * b");
    var x = myFunction(4, 3);
    use new Writing method of tense
    var myFunction = function (a, b) {return a * b};
    var x = myFunction(4, 3);
    stay JavaScript In many cases, you need to avoid using new keyword.

Function promotion:

  1. Hoisting is the behavior that JavaScript promotes the current scope to the previous one by default.
  2. Lifting is applied to the declaration of variables and functions. The function can be called before the Declaration:
  3. Cannot promote when using an expression to define a function.
    function myFunction(y) {
        return y * y;

  1. The function expression can be called by itself. If the expression is followed by (), it will be called automatically.
  2. Cannot self call a declared function
    (function () {
        var x = "Hello!!";      // I will call myself
    The above function is actually an anonymous self calling function (No function name). 
    1. Function can be used as a value
    function myFunction(a, b) {
        return a * b;
    var x = myFunction(4, 3);
    2. Functions can be used as expressions
    function myFunction(a, b) {
        return a * b;
    var x = myFunction(4, 3) * 2;

Functions are objects

  1. Using the typeof operator to judge the function type in JS will return function
  2. JS functions are more accurately described as an object. JS functions have properties and methods, such as arguments The length property returns the number of parameters received during the function call:
    function myFunction(a, b) {
        return arguments.length;
    toString() Method returns the function as a string:
   function myFunction(a, b) {
        return a * b;
    var txt = myFunction.toString();
    A function defines an attribute as an object, which is called an object method
    If the function is used to create a new object, it is called the constructor of the object

Arrow function: new arrow function in ES6.

  1. (parameter 1, parameter 2,..., parameter n) = > {function declaration}
  2. (parameter 1, parameter 2,..., parameter n) = > expression (single) / / equivalent to: (parameter 1, parameter 2,..., parameter n) = > {return expression;}
    When there is only one parenthesis:
        (Single parameter) => {Function declaration}
         Single parameter => {Function declaration}
    Functions without arguments should be written in parentheses:
        () => {Function declaration}
    // ES5
    var x = function(x, y) {
         return x * y;
    // ES6
    const x = (x, y) => x * y;
  1. Some arrow functions do not have their own this, which is not suitable for defining an object method. When we use the arrow function, the arrow function will help us bind the value of the outer layer this by default, so the value of this in the arrow function is the same as that in the outer layer this.
  2. Arrow functions cannot be promoted, so they need to be defined before use
  3. const is safer than var because the function expression is always a variable
  4. If the function part is just a statement, you can omit the return keyword and braces {}
  5. The arrow function is not supported in IE11 and earlier IE versions

JS function does not check the value of parameters: JS parameters include explicit parameters and implicit parameters

    Explicit arguments to functions:
    functionName(parameter1, parameter2, parameter3) {
        // Code to execute
    1. The function display parameters are listed when the function is defined
    2. Function implicit parameters are passed to the true value of the function when the function is called

Type of parameter

  1. JS function does not specify a data type when explicitly defining parameters
  2. JS function does not type detect implicit parameters
  3. JS function does not detect the number of implicit parameters
  4. In ES5, if the function does not provide an implicit parameter when calling, the parameter will be set to undefine by default
    Sometimes the above fourth rule is acceptable, but it is recommended to set a default value for the parameter
    function myFunction(x, y) {
        if (y === undefined) {
              y = 0;
    Or a simpler way
    function myFunction(x, y) {
        y = y || 0;
    1. If y Already defined, y||return y,because y yes true ,Otherwise, it returns 0 because undefine by false
    2. If too many parameters are set during function call, the parameters cannot be called because the corresponding parameter name cannot be found and can only be used arguments Object.

ES6 function can have its own parameters

  1. ES6 supports functions with default parameters to judge undefined and 𞓜 operations
    function myFunction(x, y = 10) {
        // y is 10 if not passed or undefined
        return x + y;
    myFunction(0, 2) // Output 2
    myFunction(5); // Output 15, default value of Y parameter

arguments object

  1. JS function built-in arguments object: contains the parameter array of the function call
  2. Through the arguments object, we can easily print out the values of all parameters

Pass parameters by value

  1. The implicit parameter of the function when the parameter is called in the function, and the JS implicit parameter is passed by the value.
  2. If the function modifies the value of the parameter, the initial value of the display parameter (defined outside the function) is not modified
  3. The change of implicit parameters cannot be changed outside the function

Passing parameters through objects

  1. In JS, the value of an object can be referenced, so if we modify the attribute of an object within a function, we will modify its initial value
  2. Modifying object attributes can act outside the function (global variables), and modifying object attributes is visible outside the function

There are 4 ways to invoke the JS function. The difference between each method is the initialization of this.

  1. This keyword. Generally speaking, this keyword points to the current object when the function is executed. Note that this is a reserved keyword and the value of this cannot be modified
  2. Call JS function: call as a function.
    function myFunction(a, b) {
        return a * b;
    myFunction(10, 2);           // myFunction(10, 2) returns 20

    1. The above function does not belong to any object, but in JS In, it is always the default global object
    2. stay html In, the default global object is html The page itself, so the function belongs to html page
    3. The page object in the browser is the browser window(window object),The above functions will automatically become window Function of object
    4. myFunction() and window.myFunction() It's the same:
    function myFunction(a, b) {
        return a * b;
    window.myFunction(10, 2);    // window.myFunction(10, 2) returns 20

When the function is not called by its own object, the value of this will become a global object.

  1. In a web browser, the global object is the browser window (window object)
    function myFunction() {
        return this;
    myFunction();                // Return window object
    Function is called as a global object this The value of is a global object, using window Object as a variable is easy to cause program crash

Function is called as a method

  1. In JS, functions can be defined as methods of objects.
    1. Created an object (myObject), Object has two properties (firstName and lastName), And a method (fullName):
    var myObject = {
        lastName: "Doe",
        fullName: function () {
            return this.firstName + " " + this.lastName;
    myObject.fullName();         // Return to "John Doe"
    2. fullName Method to make a function, which belongs to an object, myObject Make the owner of the function
    3. this Object, owning JS Code, in Example this The value of is myObject object
    var myObject = {
    lastName: "Doe",
    fullName: function () {
            return this;
    myObject.fullName();          // Return to [object Object]
    Function is called as an object method, which will make this The value of becomes the object itself.

Calling functions using constructors

  1. If the new keyword is used before the function call, the call is used in the constructor
  2. In fact, the function new is not used to re create the new object
    // Constructor:
    function myFunction(arg1, arg2) {
        this.firstName = arg1;
        this.lastName  = arg2;
    // This    creates a new object
    var x = new myFunction("John","Doe");
    x.firstName;                             // Return to "John"
    1. The call of the constructor will create a new object, which will inherit the properties and methods of the constructor
    2. In constructor this The key sub word has no value, this The value of is instantiated in a function call (new object) Create when

Call a function as a function method

  1. In JS, functions are objects, and JS functions have their properties and methods
  2. call() and apply() are predefined function methods, which can be used to call functions
    The first argument to both methods must be the object itself.
    function myFunction(a, b) {
        return a * b;
    myObject =, 10, 2);     // Return to 20
    function myFunction(a, b) {
        return a * b;
    myArray = [10, 2];
    myObject = myFunction.apply(myObject, myArray);  // Return to 20
  1. Both call() and apply() use the object itself as the first parameter. The difference between them lies in the second parameter
  2. The second parameter of apply() is passed in a parameter array, that is, multiple parameters are combined into an array
  3. The second parameter of call() is passed into call (starting from the second parameter) as the parameter of call()
  4. In JS strict mode, when calling a function, the first parameter will become the value of this, even if the parameter is not an object
  5. If the first parameter of the object is null or null, it will be replaced by the value of the first parameter in the strict mode of jsefine
  6. Through the call() or apply() methods, you can set the value of this and call it as a new method of an existing object.

Detailed explanation of JS closure

  1. JS variables can be local variables or global variables: global and local variables are two different variables even if they have the same name. Modifying one of them will not affect the value of the other.
  2. If the var keyword is not used in variable declaration, it is a global variable and will not affect its definition in the function
    Global variables: functions can access variables defined internally by the function
    function myFunction() {
        var a = 4; a Is a local variable, which can only be used to define its internal function. It is not available for other functions or script code
        return a * a;
    Functions can also access variables defined outside the function:
    var a = 4;here a Is a global variable, in web In the page, the global variable belongs to window Object, global variables can be applied to all scripts on the page
    function myFunction() {
        return a * a;

Variable life cycle

  1. The scope of global variables is global, that is, in the whole JS program, all variables are everywhere
  2. Variables declared inside the function only work inside the function. These variables are local variables and the scope is local; The parameters of a function are also local and only work inside the function.

In JS, all functions can access the scope of their upper layer

  1. JS supports nested functions, which can access the function variables of the upper layer
    function add() {
        var counter = 0;
        function plus() {counter += 1;}
        return counter; 

  1. In the instance, the embedded function pull() can access the counter variable,
    var add = (function () {
        var counter = 0;
        return function () {return counter += 1;}
    // The counter is 3
  1. The variable add specifies the return word value of the function self call. The self calling function executes only once, sets the count to 0, and returns the function expression. The add variable can be used as a function and can access the counters of the scope of the upper layer of the function. This is JS closure! At this time, the counter is protected by the scope of the anonymous function and can only be modified through the add method
  2. JS closure: closure is a mechanism to protect private variables. It forms a private scope during function execution to protect the private variables from external interference. Intuitively, it is to form a stack environment that is not destroyed.

HTML DOM tree model of JS

  1. Through HTML DOM (Document Object Model): when the web page is loaded, the browser will create the document object model of the page
  2. The HTML DOM model is constructed as a tree of objects:

[the external chain picture transfer fails. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-QGLKZla3-1620288964479)(:/289c116bb20343109aa0bf71997db02d)]

  1. Through the programmable object model, JS has the ability to create dynamic html, change all html elements, attributes and CSS styles in the page, and respond to all events in the page
  2. html elements can be found by id, tag name and class name
    1. stay DOM Find in HTML The simplest way to element is by using the id. If the element is found, the method takes the object x Returns the element as. If the element is not found, the x Will contain null. 
        var x=document.getElementById("intro");
    2.This example finds id="main" And then find id="main" All in element <p> Element:
        var x=document.getElementById("main");
        var y=x.getElementsByTagName("p");
    3.This example passed getElementsByClassName Function to find class="intro" Elements of:
        var x=document.getElementsByClassName("intro");

Use the DOM of JS to change html

  1. In JS, document Write() can be used to write content directly to the HTML output stream.
  2. Never use document after the document (DOM) is loaded write(). This overwrites the document.
  3. The easiest way to modify HTML content is to use the innerHTML attribute. document.getElementById(id).innerHTML = new HTML
  4. Change the attribute of HTML element: document getElementById(id). Attribute = new attribute value
  5. Change the style of HTML elements: document getElementById(id). style. Property = new style

html DOM event of JS

  1. Execute JavaScript when an event occurs, such as when a user clicks on an HTML element.
  2. Common events: when the user clicks the mouse, when the web page is loaded, when the image is loaded, when the mouse moves over the element, when the input field is changed, when submitting the html form, when the user triggers the key
  3. If you need to assign events to html, use event properties. Assign onclick event to button element: button onclick = "displayDate()" > Click here < / button > the function named displayDate will be executed when the button is clicked.
  4. The HTML DOM allows you to use JavaScript to assign events to HTML elements:
    be known as displayDate The function of is assigned to id="myBtn" of HTML Element. When the button is clicked Javascript The function will be executed.
  1. onload and onunload events are triggered when the user enters or leaves the page.
  2. The onload event can be used to detect the browser type and browser version of the visitor, and load the correct version of the web page based on this information.
  3. onload and onunload events can be used to handle cookie s.
  4. Onchange events are often used in conjunction with validation of input fields. When the user changes the content of the input field, the uppercase() function is called< input type="text" id="fname" onchange="upperCase()">
  5. onmouseover and onmouseout events can be used to trigger functions when the user's mouse moves over or out of an HTML element.
  6. onmousedown, onmouseup and onclick constitute all parts of the mouse click event. First, the onmousedown event will be triggered when the mouse button is clicked, the onmouseup event will be triggered when the mouse button is released, and finally, the onclick event will be triggered when the mouse click is completed.

JS html DOM EventListener

  1. addEventListener() method: trigger the listening event when the user clicks the button: document getElementById(“myBtn”). addEventListener(“click”, displayDate);
  2. The addEventListener() method is used to add an event handle to the specified element. You can add multiple event handles
  3. The event handle added by the addEventListener() method will not overwrite the existing event handle.
  4. You can add multiple event handles of the same type to the same element, such as two "click" events.
  5. You can add event listeners to any DOM object, not just HTML elements. For example: window object.
  6. The addEventListener() method makes it easier to control events (bubbling and capturing).
  7. When you use the addEventListener() method, JavaScript is separated from HTML tags and is more readable. You can also add event listeners when you do not control HTML tags.
  8. Use the removeEventListener() method to remove the listener of the event.

Addeventlistener syntax: element addEventListener(event, function, useCapture);

  1. The first parameter is the type of event (such as "click" or "mousedown")
  2. The second parameter is the function that is called after the event is triggered.
  3. The third parameter is a Boolean value that describes whether the event is bubbling or captured. This parameter is optional.
  4. Note: do not use the "on" prefix. For example, use "click" instead of "onclick".
    1. Pop up when the user clicks on the element "Hello World!" :
        element.addEventListener("click", myFunction);
        function myFunction() {
            alert ("Hello World!");
    2.You can add different types of events to the same element:
        element.addEventListener("mouseover", myFunction);
        element.addEventListener("click", mySecondFunction);
        element.addEventListener("mouseout", myThirdFunction);
    3.  addEventListener() Methods allow you to HTML DOM Object to add event listening, HTML DOM Objects such as: HTML element, HTML file, window Object. Or other supported event objects, such as: xmlHttpRequest Object.
    4.Add event listening when the user resets the window size:
        window.addEventListener("resize", function(){
            document.getElementById("demo").innerHTML = sometext;
    5.When passing parameter values, use"Anonymous function"Call a function with parameters:
        element.addEventListener("click", function(){ myFunction(p1, p2); });
    6. removeEventListener() Method removed by addEventListener() Method:
        element.removeEventListener("mousemove", myFunction);

There are two ways to pass JS events: bubbling and capturing.

  1. Event passing defines the sequence in which element events are triggered.
  2. In bubbling, the event of the internal element will be triggered first, and then the external element, that is:

    The click event of the element is triggered first and then triggered

    Click event of element.

  3. During capture, the events of external elements will be triggered first, and then the events of internal elements will be triggered, that is:
    The click event of the element is triggered first, and then triggered again

    Click event of element.

    addEventListener() Method can be specified "useCapture" Parameter to set the transfer type:
    addEventListener(event, function, useCapture);
    The default value is false, That is, bubbling transmission, when the value is true Time, Events are passed using capture.
    document.getElementById("myDiv").addEventListener("click", myFunction, true);

JS html DOM element (node)

  1. To create a new HTML element (node), you need to create an element first, and then add it to the existing element.
  2. Create a new HTML element (node) - appendChild()
    <div id="div1">
    <p id="p1">This is a paragraph.</p>
    <p id="p2">This is another paragraph.</p>
    var para = document.createElement("p");
    var node = document.createTextNode("This is a new paragraph.");
    var element = document.getElementById("div1");
  1. Create P element: VAR para = document createElement("p");
  2. Create a new text node for the p element: VAR node = document CreateTextNode ("this is a new paragraph");
  3. Add a text node to the p element: para appendChild(node);
  4. Find the existing element: VAR element = document getElementById("div1");
  5. Add an existing element: element appendChild(para);

Create a new html element node - inserBefore()

    <div id="div1">
    <p id="p1">This is a paragraph.</p>
    <p id="p2">This is another paragraph.</p>
    var para = document.createElement("p");
    var node = document.createTextNode("This is a new paragraph.");
    var element = document.getElementById("div1");
    var child = document.getElementById("p1");
    element.insertBefore(para, child);

Remove existing elements

    1. Early Internet Explorer Browser does not support node.remove() method.
    <div id="div1">
    <p id="p1">This is a paragraph.</p>
    <p id="p2">This is another paragraph.</p>
    var parent = document.getElementById("div1");
    var child = document.getElementById("p1");
    2. Know the child element to be found, then find its parent element, and then delete the child element (the parent node must be known for deleting the node):
        var child = document.getElementById("p1");

Replace HTML element – replaceChild()

    <div id="div1">
    <p id="p1">This is a paragraph.</p>
    <p id="p2">This is another paragraph.</p>
    var para = document.createElement("p");
    var node = document.createTextNode("This is a new paragraph.");
    var parent = document.getElementById("div1");
    var child = document.getElementById("p1");
    parent.replaceChild(para, child);

JS html DOM collection

    1. getElementsByTagName() Method return HTMLCollection Object.
        var x = document.getElementsByTagName("p");
    2. Elements in a collection can be indexed(Start with 0)To visit. Visit the second 3. <p> The element can be the following code:y = x[1];
    4. HTMLCollection Object length Attribute defines the number of elements in the collection.
        var myCollection = document.getElementsByTagName("p");
        document.getElementById("demo").innerHTML = myCollection.length;
    5. HTMLCollection It may look like an array, but it's not. However, you can use indexes to get elements.
    6. HTMLCollection Cannot use array method: valueOf(), pop(), push(), or join() . 

Everything in JS is an object: string, value, array, function

  1. JS allows custom objects
  2. JavaScript provides multiple built-in objects, such as String, Date, Array, and so on. Objects are just special data types with properties and methods.
  3. Common JS objects: Boolean, numeric, string, date, regular expression, array, function
  4. Attributes are object related values, and the syntax for accessing object attributes is objectname propertyNamevar message=“Hello World!”;`
    var message="Hello World!";
    var x=message.length;  //12
  1. The method is to be able to perform actions on the object: objectname methodName()
    var message="Hello world!";
    var x=message.toUpperCase(); //HELLO WORLD!
  1. There are two different ways to create objects;
    1. Use Object to define and create an instance of the Object.
    2. Use the function to define the object, and then create a new object instance.

  2. Create objects with Object: in JS, almost all objects are instances of Object type, and they will be created from Object Prototype inherits properties and methods.

  3. The Object function constructor creates an Object wrapper to create an Object based on the given parameters

  4. If the given value is null or undefined, an empty object will be created and returned.

  5. If a value of a basic type is passed in, an object of its wrapper type will be constructed.

  6. If a value of reference type is passed in, this value will still be returned, and the variable copied by them will keep the same reference address as the source object.

  7. When called in a non constructor form, the behavior of Object is equivalent to new Object().

Added by serial on Thu, 17 Feb 2022 22:19:01 +0200