JavaScript basic skill training

Posted by raytri on Fri, 21 Jan 2022 17:24:42 +0100

JavaScript basic syntax

  • HTML: markup language
  • JavaScript: programming language

preface

JavaScript development history (JS)

1. 1994 Netscape, Inc(Netscape)Released Navigator Browser 0.9 This is the first mature web browser in the world. But this is a veritable browser--You can only browse the page, and the browser cannot interact with users,At that time, there were two ways to solve this problem. One was to use the existing language,Allow them to be embedded directly in web pages. The other is to invent a new language.
	liveScript ==> javaScript ==> ECMAscript

2. 1995 year Sun The company will Oak Language renamed Java,Officially launched to the market. Sun The company hyped and promised that the language could be used"Write once and ship everywhere	 that 's ok"(Write Once, Run Anywhere),It looks likely to dominate the future.

3. Netscape company moved and decided to cooperate with Sun The company formed an alliance

4. 34 Year old system programmer Brendan Eich Here we go. In April 1995, Netscape hired him,It took him only 10 days to finish the job Javascript It's designed. (polypeptide language)

5.
	(1)draw lessons from C Basic grammar of language
	(2)draw lessons from Java Data type and memory management of language
	(3)draw lessons from Scheme Language to promote functions to"First class citizen"(first class)Status of
	(4)draw lessons from Self Language, using prototype based(prototype)Inheritance mechanism of

What can JavaScript do

1. Common web page effects [form verification, rotation diagram...]
2. And H5 Cooperate to realize the game [Fruit Ninja: http://www.jq22.com/demo/html5-fruit-ninja/]
3. Implement application level applications[ http://naotu.baidu.com]
4. Achieve statistical effect[ http://echarts.baidu.com/examples/]
5. Geographic positioning and other functions[ http://lbsyun.baidu.com/jsdemo.htm#i4_5]
6. Online learning programming[ https://codecombat.163.com/play/]
7. js It can realize artificial intelligence [face recognition]
8. . . . 

Composition of JavaScript

1. ECMASCRIPT: Defined javascript Syntax specification of,Describes the basic syntax and data types of the language
2. BOM (Browser Object Model): Browser object model
  - There is a set of mature software that can operate the browser API,adopt BOM You can operate the browser. For example: pop-up box, browser jump, obtaining resolution, etc
3. DOM (Document Object Model): Document object model
  - There is a mature set of methods that can operate page elements API,adopt DOM You can manipulate elements in a page. For example, add one div,Reduce div,to div Change position, etc

Summary: JS is to operate the browser and tag structure through fixed syntax to achieve various effects on Web pages

Writing position of JavaScript code

  • Like css, our js can be written on the page in many ways to make it effective
  • js can also be written in many ways, including inline, embedded and external chain

Inline JS code (not recommended)

  • The js code written on the tag needs to be triggered by events (behaviors)
<!-- Write in a Tagged href Attribute -->
<a href="javascript:alert('I am a pop-up layer');">Click to try</a>

<!-- Write on other elements -->
<div onclick="alert('I am a pop-up layer')">Click and try</div>

<!--
	Note: onclick Is an event (click event) that executes the following when an element is clicked js code
-->

Embedded JS code

  • The embedded js code will be triggered directly when the page is opened
<!-- stay html Write a page script Label, written inside the label js code -->
<script type="text/javascript">
	alert('I am a pop-up layer')
</script>

<!--
	Note: script Labels can be placed on head It can also be placed inside body inside
-->

External chain JS code (recommended)

  • As long as the html page is introduced into the external linked js code, it will be triggered directly when the page is opened
  • Create a new one js suffix file, write js code in the file, and introduce the written js file into the html page
// I'm index JS file
alert('I am a pop-up layer')
<!-- I am a html file -->

<!-- adopt script Tagged src Attribute, write it js File import page -->
<script src="index.js"></script>

<!-- One page can introduce multiple js file -->
<script src="index1.js"></script>
<script src="index2.js"></script>
<script src="index3.js"></script>

Comments in JS

  • To learn a language, first learn the annotation of a language, because the annotation is for ourselves and developers
  • Write a comment that will help us read the code later

Single-Line Comments

  • It is generally used to describe the function of the following line of code
  • You can write two /, or press ctrl +/
// I'm a single line note

// The following code indicates that a pop-up layer appears in the browser
alert('I am a pop-up layer')

multiline comment

  • It is usually used to write a long paragraph or comment on a piece of code
  • You can write / * * / directly, and then write a comment between the two asterisks
    • The shortcut keys of each editor are different. vscode is ctrl + shift + a
/*
	I am a multiline comment
*/

/*
	Commented code is not executed
	alert('I am a pop-up layer ')
	alert('I am a pop-up layer ')
*/
alert('I am a pop-up layer')

Variable (key)

  • A variable is a container that holds data in a program
  • Variable is the identifier of data stored in computer memory. The data stored in memory can be obtained according to the variable name
  • In other words, we store a data in memory, and then we need to give a name to the data, so that we can find it again in the future
  • Syntax: var variable name = value

Defining variables and assignment

// Define a variable
var num;

// Assign a value to a variable
num = 100;

// Define a variable and assign a value to it at the same time
var num2 = 200;
  • be careful:
    1. A variable name can store only one value
    2. When you assign a value to a variable again, the previous value is gone
    3. Variable names are case sensitive (JS is strictly case sensitive)

Naming rules and norms of variables

  • Rule: what must be observed, failure to observe is wrong

    1. A variable name can be composed of numbers, letters, English underscores () Dollar sign ($)
    2. Strictly case sensitive
    3. Cannot start with a number
    4. Cannot be a reserved word or keyword
    5. No spaces
  • Specification: it is recommended to comply with (default by the developer). No error will be reported if it is not complied with

    1. Make variable names as meaningful as possible (semantically)
    2. Follow the hump naming rules. When multiple words are composed, the first letter shall be capitalized from the second word
    3. Do not use Chinese

Data type (key)

  • It refers to the type of data we store in memory
  • We usually divide into two categories: basic data types and complex data types

Basic data type

  1. Value type (number)
    • All numbers are numeric types (including binary, decimal, hexadecimal, etc.)
    • NaN (not a number), a non number
  2. String type (string)
    • Everything enclosed in quotation marks (single quotation marks or double quotation marks)
  3. boolean type
    • Only two (true or false)
  4. Null type (null)
    • There is only one, null, which means empty
  5. Undefined type (undefined)
    • Only one is undefined, which means there is no value

Complex data types (not for now)

  1. Object type (object)
  2. function type
  3. . . .

Judge data type

  • Now that we have separated the data types, we need to know what type of data we store
  • Use the typeof keyword to judge
// The first use method var n1 = 100;console.log(typeof n1);//  The second method is var s1 = 'abcdefg';console.log(typeof(s1));

Determine whether a variable is a number

  • isNaN can be used to judge whether a variable is a number
  • isNaN : is not a number
// If the variable is a number, VAR N1 = 100; console. log(isNaN(n1)); //=>  False / / if the variable is not a number, VAR S1 = 'Jack' console log(isNaN(s1)); //=>  true

Data type conversion

  • Conversion between data types, such as number to string, string to Boolean, Boolean to number, etc

Convert other data types to values

  1. Number (variable)

    You can cast a variable to a numeric type

    Decimals can be converted and retained

    Boolean values can be converted

    NaN will be returned in case of non convertible

  2. ParseInt (variable)

    Check from the first place. If it is a number, it will be converted to know a content that is not a number

    If the beginning is not a number, then NaN is returned directly

    Do not know the decimal point, only integer can be retained

  3. Parsefloat (variable)

    Check from the first place. If it is a number, it will be converted to know a content that is not a number

    If the beginning is not a number, then NaN is returned directly

    Know the decimal point once

  4. Mathematical operations other than addition

    Operators are operable numbers on both sides

    If any one pass of the operator is not an operable number, NaN is returned

    Addition cannot be used

Convert other data types to strings

  1. Variable toString()

    Some data types cannot use toString() methods, such as undefined and null

  2. String (variable)

    All data types are OK

  3. Use addition

    In JS, + has two meanings

    String splicing: String splicing will be carried out as long as + is a string on either side

    Addition operation: only when both sides of + are numbers can mathematical operation be carried out

Convert other data types to Boolean

  1. Boolean (variable)

    In js, only '', 0, null, undefined and NaN are false

    The rest are true

operator

  • It is the symbols used in the operation in the code. It is not only mathematical operation, but also there are many operation methods in js

Mathematical operator

  1. +

    Addition is performed only when there are numbers on both sides of the symbol

    String splicing is performed as long as either side of the symbol is a string type

  2. -

    Can perform subtraction

    It will automatically convert both sides into numbers for operation

  3. *

    Can perform multiplication

    It will automatically convert both sides into numbers for operation

  4. /

    Can perform division

    It will automatically convert both sides into numbers for operation

  5. %

    Can perform remainder operation

    It will automatically convert both sides into numbers for operation

Assignment Operators

  1. =

    Is to assign the value on the right of = to the variable name on the left of the equal sign

    var num = 100

    Is to assign 100 to the num variable

    Then the value of the num variable is 100

  2. +=

    var a = 10;a += 10;console.log(a); //=> 20
    

    a += 10 is equivalent to a = a + 10

  3. -=

    var a = 10;

    a -= 10;console.log(a); //=> 0
    

    a -= 10 is equivalent to a = a - 10

  4. *=

    var a = 10;a *= 10;console.log(a); //=> 100
    

    a *= 10 is equivalent to a = a * 10

  5. /+

    var a = 10;a /= 10;console.log(a); //=> 1
    

    a /= 10 is equivalent to a = a / 10

  6. %=

    var a = 10;a %= 10;console.log(a); //=> 0
    

    A% = 10 is equivalent to a = a% 10

Comparison operator

  1. ==

    • Compares whether the values on both sides of the symbol are equal, regardless of the data type

      1 == '1'

      The two values are the same, so you get true

  2. ===

    • Compare whether the values and data types on both sides of the symbol are equal

      1 === '1'

      Although the two values are the same, they get false because the data types are different

  3. !=

    • Compare whether the values on both sides of the symbol are unequal

      1 != '1'

      Because the values on both sides are equal, we get false when comparing them

  4. !==

    • Compare whether the data types and values on both sides of the symbol are different

      1 !== '1'

      Because the data types on both sides are really different, you get true

  5. >=

    • Compare whether the value on the left is greater than or equal to the value on the right

      1 > = the result is true

      1 > = 0 results in true

      1 > = 2 the result is false

  6. <=

    • Compare whether the value on the left is less than or equal to the value on the right

      1 < = 2 the result is true

      1 < = 1 the result is true

      1 < = 0 result is false

  7. >

    • Compare whether the value on the left is greater than the value on the right

      1 > 0 results in true

      1 > 1 the result is false

      1 > 2 the result is false

  8. <

    • Compare whether the value on the left is less than the value on the right

      1 < 2 results in true

      1 < 1 results in false

      1 < 0 result is false

Logical operator

  1. &&

    • Operations performed and

      The left side of the symbol must be true and the right side must be true to return true

      As long as one side is not true, false will be returned

      True & & true the result is true

      True & & false the result is false

      False & & true the result is false

      False & & false the result is false

  2. ||

    • Operation of or

      If the left side of the symbol is true or the right side is true, true will be returned

      False is returned only when both sides are false

      True | true the result is true

      True | false the result is true

      False | true the result is true

      False | false the result is false

  3. !

    • Inverse operation

      If it is true, it will become false

      If it is false, it will become true

      ! true the result is false

      ! false the result is true

Self increasing and self decreasing operator (unary operator)

  1. ++

    • Self increment operation

    • There are two types, pre + + and post++

    • Pre + +, the value will be automatically + 1 before returning

      var a = 10;console.log(++a);// Will return 11 and change the value of a to 11
      
    • After + +, the value will be returned first, and the value will be automatically + 1

      var a = 10;console.log(a++);// It will return 10, and then change the value of a to 11
      
  2. --

    • Perform self subtraction
    • There are two types, front – and rear –
    • It is the same as the + + operator

Branching structure

  • Our js code is executed sequentially (from top to bottom)
  • Logical branching is to decide whether to execute some code according to the conditions we set

IF conditional branch structure (key)

if statement

  • An if statement is used to determine whether the code is executed

  • Syntax: if (condition) {code to execute}

  • Whether the code in {} is executed is determined by whether the conditions in () are true

    // Execute the code in {} when the condition is true
    if (true) {
      alert('Because the condition is true,I'll do it')
    }
    
    // If the condition is false, the code in {} will not be executed
    if (false) {
    	alert('Because the condition is false,I won't do it')    
    }
    

if else statement

  • Determine which {} code to execute through the if condition

  • Syntax: if (condition) {execute when the condition is true} else {execute when the condition is false}

  • One of the two {} codes must execute

    // When the condition is true, {} after if will be executed 
    if (true) {
      alert('Because the condition is true,I'll do it')
    } else {
      alert('Because the condition is true,I won't do it')
    }
    
    // When the condition is false, {} after else will be executed
    if (false) {
      alert('Because the condition is false,I won't do it')
    } else {
      alert('Because the condition is false,I'll do it')
    }
    

If else... Statement

  • You can set multiple conditions for judgment through if and else if

  • Syntax: if (condition 1) {execute when condition 1 is true} else if (condition 2) {execute when condition 2 is true}

  • Will judge the conditions from the beginning

    • If the first condition is true, the contents in the following {} will be executed
    • If the first condition is false, the second condition will be judged, and so on
  • If there are multiple {}, only one will be executed. Once one condition is true, the latter will not be judged

    // The first condition is true and the second condition is false. Finally, "I am code segment 1" will be printed
    if (true) {
      	alert('I'm snippet 1')
    } else if (false) {
    	alert('I'm snippet 2')           
    }
    
    // The first condition is true, the second condition is true, and finally "I am code segment 1" will be printed
    // Because as long as one of the previous conditions is met, we will not continue to judge
    if (true) {
      	alert('I'm snippet 1')
    } else if (true) {
      	alert('I'm snippet 2')
    }
    
    // The first condition is false, the second condition is true, and finally "I am code segment 2" will be printed
    // Only when the previous condition is false will the backward judgment be continued
    if (false) {
      	alert('I'm snippet 1')
    } else if (true) {
      	alert('I'm snippet 2')
    }
    
    // The first condition is false, the second condition is false, and nothing will happen in the end
    // Because when all conditions are false, the code in both {} will not be executed
    if (false) {
      	alert('I'm snippet 1')
    } else if (false) {
      	alert('I'm snippet 2')
    }
    

If else... Else statement

  • And the previous if else if Basically consistent, except that when all conditions are not met, execute {} after the last else

    // The first condition is false, the second condition is false, and finally "I am code segment 3" will be printed
    // Only when all the previous conditions are not met will the code in {} behind else be executed
    // As long as one of the preceding conditions is met, the latter will not be executed
    if (false) {
      	alert('I'm snippet 1')
    } else if (false) {
      	alert('I'm snippet 2')
    } else {
      	alert('I'm code snippet 3')
    }
    

SWITCH conditional branch structure (key)

  • It is also a kind of conditional judgment statement

  • It is the judgment of a variable

  • Syntax:

    switch (Variables to judge) {
      case Case 1:
        Case 1 code to execute
        break
      case Case 2:
        Case 2 code to execute
        break
      case Case 3:
        Case 3 code to execute
        break
      default:
        Code executed when none of the above conditions are satisfied
    }
    
    • To determine when a variable is equal to a value, use it
  • example 🌰: The number given according to the variable shows the day of the week

    var week = 1
    switch (week) {
      case 1:
        alert('Monday')
        break
      case 2:
        alert('Tuesday')
        break
      case 3:
        alert('Wednesday')
        break
      case 4:
        alert('Thursday')
        break
      case 5:
        alert('Friday')
        break
      case 6:
        alert('Saturday')
        break
      case 7:
        alert('Sunday')
        break
      default:
        alert('Please enter a 1 ~ 7 Number between')
    }
    

Ternary operation (Extended)

  • Ternary operation is to use two symbols to form a statement

  • Ternary operation is only a short form of if else statement

  • Syntax: condition? Execute when the condition is true: execute when the condition is false

    var age = 18;
    age >= 18 ? alert('Have grown up') : alert('No adult')
    

Cycle structure (key)

  • Loop structure is to execute the same piece of code repeatedly according to some given conditions
  • The loop must have some fixed content
    1. initialization
    2. Conditional judgment
    3. Code to execute
    4. Self change

WHILE loop

  • while, which is called when in Chinese, actually means that the code will be executed when the conditions are met. Once the conditions are not met, it will not be executed

  • Syntax while (condition) {execute when condition is met}

  • Because it is executed when the conditions are met, we must pay attention to setting a boundary value when writing, otherwise it will continue to cycle

    // 1. Initialization conditions
    var num = 0;
    // 2. Condition judgment
    while (num < 10) {
      // 3. Code to execute
      console.log('Current num The value of is ' + num)
      // 4. Self change
      num = num + 1
    }
    
    • If you don't change yourself, you'll keep cycling

DO WHILE loop

  • Is a loop similar to the while loop

  • while will judge the conditions first and execute if they are met. If they are not met, they will not be executed directly

  • However, the do while loop is to execute it once regardless of the conditions, and then judge the conditions at the beginning

  • Syntax: do {code to execute} while (condition)

    // In the following code, the condition is not satisfied at the beginning, but the code behind {} do will still be executed once
    var num = 10
    do {
      console.log('I did it once')
      num = num + 1
    } while (num < 10)
    

FOR cycle

  • A loop structure that is different from while and do while loops

  • The reason is the same as the other two, which execute code in a loop

  • Syntax: for (VaR I = 0; I < 10; I + +) {code to execute}

    // The initialization, condition judgment and self change are written together
    for (var i = 1; i <= 10; i++) {
      // Here is the code to be executed
      console.log(i)
    }
    
    // The console will output 1 ~ 10 in turn 
    
  • This just doesn't look very comfortable, but it's easy to use

BREAK terminates the loop

  • When the cycle is not completed, the cycle is terminated in advance because the conditions I set are met

  • For example: I want to eat five steamed stuffed buns. When I eat three, I can't eat any more. I'll stop eating steamed stuffed buns

  • To terminate the loop, you can use the break keyword directly

    for (var i = 1; i <= 5; i++) {
      // Don't cycle once, eat a steamed stuffed bun
      console.log('I ate a steamed stuffed bun')
      // When the value of i is 3 and the condition is true, execute the code in {} to terminate the loop
      // The loop will not continue down, and there will be no 4 and 5
      if (i === 3) {
        break
      }
    }
    

CONTINUE ends this cycle

  • In the loop, skip this time of the loop and continue to execute subsequent loops

  • For example, when you eat five steamed stuffed buns, the third one falls to the ground and stops eating. Skip the third one and continue to eat the fourth and fifth

  • Skip this loop and use the continue keyword

    for (var i = 1; i <= 5; i++) {
      // When the value of i is 3, execute the code in {}
      // If there is continue in {}, the code behind this loop will not be executed
      // This time when i is automatically calculated as 3 is over, and i continue to execute the cycle with i = 4
      if (i === 3) {
        console.log('This is the third steamed stuffed bun. It fell on the ground. I won't eat it')
        continue
      }
      console.log('I ate a steamed stuffed bun')
    }
    

function

  • The functions in our code are not the same as the trigonometric functions and quadratic functions we learned at school

Concept of function

  • For js, a function is to put any piece of code in a box

  • When I want this code to execute, just execute the code in this box

  • Let's look at a piece of code first

    // This is a piece of code we wrote before
    for (var i = 0; i < 10; i++) {
      console.log(i)
    }
    
    // Function, this {} is the "box"
    function fn() {
      // This function is the code we wrote before
      for (var i = 0; i < 10; i++) {
        console.log(i)
      }
    }
    

Two stages of function (focus)

  • According to what we just said, the two stages are putting in the box and letting the code in the box execute

Function definition stage

  • The definition phase is when we put the code in a box

  • We have to learn how to put it in, that is, write a function

  • We have two ways to define declarative and assignment

Declarative

  • Use the keyword function to declare a function

  • Syntax:

    function fn() {
      // A piece of code
    }
    // Function: the keyword that declares the function, indicating that there is a function next
    // fn: the name of the function is defined by ourselves (following the naming rules and naming conventions of variable names)
    // (): must be written. It is used to place parameters (we'll talk later)
    // {}: that's where we put a piece of code (that's what we just called "box")
    

Assignment formula

  • In fact, it is the same reason that we use var keyword

  • First, use var to define a variable, and assign a function as a value to the variable directly

  • Syntax:

    var fn = function () {
      // A piece of code
    }
    // There is no need to write the name of the function after the function, because there is already a function before it
    

Function call phase

  • Just let the code in the box execute
  • Let the function execute
  • The two methods of defining functions are different, but the way of calling functions is the same

Call a function

  • The function call is to write the function name () directly

    // Declarative function
    function fn() {
      console.log('I am fn function')
    }
    
    // Call function
    fn()
    
    // Assignment function
    var fn2 = function () {
      console.log('I am fn2 function')
    }
    
    // Call function
    fn()
    
    • Note: after defining a function, if there is no function call, the code written in {} is meaningless and will be executed only after the call

Call difference

  • Although the calls of the two definitions are the same, there are still some differences

  • Declarative function: the call can be before or after definition

    // Can call
    fn()
    
    // Declarative function
    function fn() {
      console.log('I am fn function')
    }
    
    // Can call
    fn()
    
  • Assignment function: call can only be made after definition

    // Will report an error
    fn()
    
    // Assignment function
    var fn = function () {
      console.log('I am fn function')
    }
    
    // Can call
    fn()
    

Parameters of function (emphasis)

  • We have seen () when defining and calling functions

  • Now let's talk about the function of this ()

  • Is the position where the parameters are placed

  • Parameters are divided into two types: line parameters and actual parameters

    // Declarative
    function fn(Line parameters are written here) {
      // A piece of code
    }
    
    fn(The arguments are written here)
    
    // Assignment function
    var fn = function (Line parameters are written here) {
      // A piece of code
    }
    fn(The arguments are written here)
    

Role of row and argument

  1. Line parameter

    • Is a variable that can be used inside a function, but not outside a function

    • Each word is equivalent to defining a variable that can be used inside the function (follow the naming rules and naming conventions of variable names)

    • Multiple words are separated by

      // Write a parameter
      function fn(num) {
        // The variable num can be used inside the function
      }
      
      var fn1 = function (num) {
      	// The variable num can be used inside the function
      }
      
      // Write two parameters
      function fun(num1, num2) {
        // You can use num1 and num2 variables inside the function
      }
      
      var fun1 = function (num1, num2) {
        // You can use num1 and num2 variables inside the function
      }
      
    • If there are only row parameters, the variables used inside the function have no value, that is, undefined

    • The value of the row parameter is determined by the argument when the function is called

  2. Argument

    • The row parameter is assigned a value when the function is called

    • In other words, the actual content is given when calling

      function fn(num) {  // Num} / / can be used inside the function. The written argument is 100 / / in this call, the num inside the function is 100fn(100) / / in this call, the written argument is 200 / / in this call, the num inside the function is 200fn(200)
      
    • The value of the row parameter inside the function is determined by the argument passed when the function is called

    • When there are multiple parameters, they correspond one by one in order

      function fn(num1, num2) {  // Num1 and num2} / / can be used inside the function / / during this call, the written parameters are 100 and 200 / / then during this call, num1 is 100 and num2 is 200fn(100, 200)
      

Relationship between the number of parameters

  1. Row arguments are less than arguments

    • Because they correspond one by one in order

    • If there are few row parameters, you will not get the value given by the actual parameter, so there is no way to use this value inside the function

      function fn(num1, num2) {  // You can use num1 and num2} / / during this call, you pass two arguments, 100, 200 and 300 / / 100 corresponds to num1200 corresponds to num2300, and there is no corresponding variable / / so there is no way to use the value fn(100, 200, 300) of 300 by relying on variables inside the function
      
  2. There are more row arguments than arguments

    • Because they correspond one by one in order

    • Therefore, the extra row parameters have no value and are undefined

      function fn(num1, num2, num3) {  // You can use num1, num2, and num3} / / during this call, two arguments are passed. 100 and 200 / / correspond to num1 and num2 respectively / / but num3 has no argument, so the value of num3 is undefinedfn(100, 200)
      

return of function

  • Return means to give a function a return value and a termination function

Final break function

  • When I start executing the function, the code inside the function will be executed from top to bottom

  • You must wait until the code in the function is executed

  • The return keyword can stop in the middle of the function so that the subsequent code will not continue to execute

    function fn() {  console.log(1)  console.log(2)  console.log(3)    // After writing return, the following 4 and 5 will not continue to execute return console log(4)  console. Log (5)} / / function call fn()
    

Return value

  • The function call itself is also an expression, and the expression should have a value

  • After the current function is executed, there will be no result

    // For example, if 1 + 2 is an expression, the result of this expression is 3console Log (1 + 2) / / 3Function fn() {/ / execute code} / / fn() is also an expression, and there is no result in console log(fn()) // undefined
    
  • The return keyword is a result of the completion of the function

    function fn() {  // Execute the code return 100} / / at this time, after the expression FN () is executed, the result appears console log(fn()) // 100
    
    • We can use the return key inside the function to treat anything as the result of the function

Advantages of function

  • Function is the encapsulation of a piece of code, which is called when we want to call it
  • Several advantages of function
    1. Encapsulate the code to make the code more concise
    2. Reuse, just call directly when repeating functions
    3. Code execution time can be executed when we want to execute at any time

Function parameters pass the difference between basic data types and complex data types

  • As we know before, there are differences in storage between basic data types and complex data types

  • Then they are also different in assignment

  • Assignment between basic data types

    var num = 10var num2 = numnum2 = 200console.log(num) // 100console.log(num2) // 200
    
    • So I copied the value of num and gave it to the num2 variable exactly
    • There is no relationship between the two after assignment
  • Assignment between complex data types

    var obj = {  name: 'Jack'}var obj2 = objobj2.name = 'Rose'console.log(obj.name) // Roseconsole.log(obj2.name) // Rose
    
    • Because of complex data types, variables store addresses, and real contents are stored in heap space
    • Therefore, the assignment is equivalent to copying the address stored in obj to the obj2 variable
    • Now, the addresses stored in obj and obj2 variables are the same, pointing to a memory space
    • Therefore, if you use the obj2 variable to modify the content in the space, the space pointed to by obj will change accordingly

Parameters of function

  • The parameters of the function are also assigned. When the function is called, the actual parameters assign values to the line parameters

  • The rules for assigning variables are the same as before

  • Function passing basic data type

    function fn(n) {  n = 200  console.log(n) // 200}var num = 100fn(num)console.log(num) // 100
    
    • As in the previous variable assignment, a copy of the value of num is copied to the row parameter n inside the function
    • There is no relationship between the two
  • Functions pass complex data types

    function fn(o) {  o.name = 'Rose'  console.log(o.name) // Rose}var obj = {  name: 'Jack'}fn(obj)console.log(obj.name) // Rose
    
    • As in the previous variable assignment, copy a copy of the address stored in obj to the row parameter o inside the function
    • obj outside the function and row parameter o inside the function store an address and point to a storage space
    • So two variables operate on one storage space
    • The data in the space is changed inside the function
    • obj also sees the content after the change

Pre analysis (key)

  • Pre parsing is actually talking about the compilation and execution of js code
  • js is an interpretive language, which is to read and interpret the code before code execution, and then execute the code
  • In other words, when our js code is running, it will go through two links: interpreting code and executing code

Interpretation code

  • Because it is interpreted before all code is executed, it is called pre parsing (pre interpretation)

  • There are two things to explain

    • Declarative function
      • In memory, first declare that a variable name is a function name, and the content represented by this name is a function
    • var keyword
      • Declare a variable name in memory first
  • Look at the following code

    fn()console.log(num)function fn() {  console.log('I am fn function')}var num = 100
    
  • After pre parsing, it can be deformed into

    function fn() {  console.log('I am fn function')}var numfn()console.log(num)num = 100
    
  • The assignment function will be pre parsed according to the rules of var keyword

Scope (key)

  • What is a scope is the range within which a variable can take effect
  • Variables can not be used everywhere, and the scope of use of this variable is the scope

global scope

  • The global scope is the largest scope

  • Variables defined in the global scope can be used anywhere

  • When the page opens, the browser will automatically generate a global scope window for us

  • This scope will exist until the page is closed and destroyed

    // The following two variables exist under the global scope and can be used anywhere
    var num = 100
    var num2 = 200
    

Local scope

  • A local scope is a relatively small scope created under the global scope

  • Variables defined in a local scope can only be used within this local scope

  • In JS, only functions can generate a local scope, nothing else

  • Every function is a local scope

    // This num is a variable under the global scope and can be used anywhere
    var num = 100
    
    function fn() {
      // The following variable is a fn local scope variable
      // Can only be used inside fn functions
      var num2 = 200
    }
    
    fn()
    

Variable usage rules (key points)

  • With a scope, variables have a scope of use and rules of use
  • There are two kinds of variable usage rules, access rules and assignment rules

Access rules

  • When I want to get the value of a variable, we call this behavior access

  • Rules for getting variables:

    • First, search within your scope. If there is any, use it directly
    • If not, go to the upper scope to find it. If yes, use it
    • If not, continue to search the upper scope, and so on
    • If there is no such variable up to the global scope, an error will be reported directly (the variable is not defined)
    var num = 100
    
    function fn() {
      var num2 = 200
      
      function fun() {
        var num3 = 300
        
        console.log(num3) // It's in your scope. Take it and use it
        console.log(num2) // If you don't have it in your scope, go to the next level, that is, find it in the scope of fn. If you find it, take it and use it
        console.log(num) // If you don't have one, you don't have one at the upper level. If you go to the global scope, you can use it directly
        console.log(a) // If you don't have one, you'll report an error if you can't find the overall situation level by level
      }
      
      fun()
    }
    
    fn()
    
  • Variable access rules are also called scope lookup mechanisms

  • The search mechanism of the scope can only be upward, not downward

    function fn() {
      var num = 100
    }
    fn()
    
    console.log(num) // If you find that you have no scope, you are the global scope. If you have no higher level, you will directly report an error
    

Assignment rules

  • When you want to assign a value to a variable, you must first find the variable and assign it

  • Variable assignment rules:

    • First search within your scope, and assign values directly if any
    • If not, go to the internal search of the upper level scope, and if there is, assign a value directly
    • Before going to the upper level scope for search, you can assign values directly
    • If the global scope is not found all the time, define this variable as a global variable and assign a value to it
    function fn() {
      num = 100
    }
    fn()
    
    // After fn is called, assign a value to num
    // Check that there is no num variable inside your scope
    // Will look up one level
    // The upper level is the global scope, and it is still not found
    // Then num will be defined as a global variable and assigned a value
    // Therefore, after fn(), there is a global variable called num and the value is 100
    console.log(num) // 100
    

Common events

Mouse event

  • Click: click event
  • dblclick: double click the event
  • Context menu: right click the event
  • mousedown: left mouse button press event
  • mouseup: left mouse button lift event
  • mousemove: mouse movement
  • mouseover: mouse in event
  • mouseout: mouse out event
  • mouseenter: mouse in event
  • mouseleave: mouse move out event
  • ...

Keyboard events

  • keyup: keyboard lift event
  • keydown: keyboard press event
  • keypress: keyboard press event
  • ...

Form Events

  • Change: form content change event
  • Input: form content input event
  • blur: form loses focus
  • Focus: get the focus of the form
  • ...

Simple understanding of objects

  • Object is a complex data type

  • In fact, it's complex, but it's not very complex. It's just a collection that stores some basic data types

    var obj = {
      num: 100,
      str: 'hello world',
      boo: true
    }
    
  • The {} here is different from the {} in the function

  • Functions write code, while objects write data

  • An object is a collection of key value pairs

  • Every key in {} is a member

  • In other words, we can put some data in an object, so they won't interfere with each other

  • In fact, we prepare a house, put in the data we want, and then give the address of the house to the variable name. When we need a certain data, we can find the corresponding house according to the address stored in the variable name, and then go to the house to find the corresponding data

Create an object

  • Create an object literally

    // Create an empty object
    var obj = {}
    
    // Add members to objects like
    obj.name = 'Jack'
    obj.age = 18
    
  • Create objects with built-in constructors

    // Create an empty object
    var obj = new Object()
    
    // Add members to objects
    obj.name = 'Rose'
    obj.age = 20
    
    • Object is a constructor built into js for creating an object

array

  • What is an array?

  • Literally, it's a combination of numbers

  • In fact, it is not accurate. To be exact, an array is a collection of data

  • That is, we put some data in a box and arrange them in order

    [1, 2, 3, 'hello', true, false]
    
  • This thing is an array that stores a collection of data

Data type classification

  • number / string / boolean / undefined / null / object / function / array / ...

  • Array is also one of the data types

  • We simply divide all data types into two categories: basic data types and complex data types

  • Basic data type: number / string / boolean / undefined / null

  • Complex data types: object / function / array /

Create an array

  • An array is a []
  • Various data are stored in [] and arranged in order

Literal creates an array

  • Create an array directly using []

    // Create an empty array
    var arr1 = []
    
    // Create an array with content
    var arr2 = [1, 2, 3]
    

Creating arrays with built-in constructors

  • Use js' built-in constructor Array to create an Array

    // Create an empty array
    var arr1 = new Array()
    
    // Create an array with a length of 10
    var arr2 = new Array(10)
    
    // Create an array with content
    var arr3 = new Array(1, 2, 3)
    

length of array

  • Length: the meaning of length

  • Length is the length of the array. The length is the number of members in the array

    // Create an array
    var arr = [1, 2, 3]
    
    console.log(arr.length) // 3
    

Index of array

  • Index, also known as subscript, refers to the position of a data in the array

  • Note: in all languages, the index starts from 0

  • The same is true in js. The index of the array starts from 0

    // Create an array
    var arr = ['hello', 'world']
    
  • In the above array, the 0th data is the string hello, and the 1st data is the string world

  • If you want to get the number in the array, use the array [index] to get it

    var arr = ['hello', 'world']
    
    console.log(arr[0]) // hello
    console.log(arr[1]) // world
    

Storage differences between data types (key points)

  • Now that we distinguish between basic data types and complex data types
  • Then there must be some differences between them
  • Their biggest difference is in storage
  • Our storage space is divided into two types: stack and heap
  • Stack: mainly stores the contents of basic data types
  • Heap: mainly stores the contents of complex data types

Storage of basic data types in memory

  • var num = 100, storage in memory
  • [the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (IMG nglcoq8m-1626013036395) (C: / users / simple point / Desktop / profile / assets / storage of basic data types in memory. png)]
  • A data is stored directly in the stack space

Storage of complex data types in memory

  • Here is the storage of this object

    var obj = {
      name: 'Jack',
      age: 18,
      gender: 'male'
    }
    
  • [the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-rCN7TyNR-1626013036397)(C:/Users / simple point / Desktop / profile / assets / storage of complex data types in memory. png)]

  • Storage of complex data types

    1. Create a storage space in the heap
    2. Store data in storage space
    3. Assign the address of the storage space to the variable in the stack
  • This is the difference between data types

Comparison between data types

  • The basic data type is a comparison between values

    var num = 1
    var str = '1'
    
    console.log(num == str) // true
    
  • Complex data types are comparisons between addresses

    var obj = { name: 'Jack' }var obj2 = { name: 'Jack' }console.log(obj == obj2) // false
    
    • Because we have created two objects, we will open up two storage spaces in the heap space to store data (two addresses)
    • Although the stored content is the same, it is also two storage spaces and two addresses
    • Complex data types are address comparisons, so the addresses of obj and obj2 variables are different
    • So what we get is false

Common methods of array

  • Array is a complex data type. When we operate it, we can no longer operate like the basic data type

  • For example, we want to change an array

    // Create an array var arr = [1, 2, 3] / / we want to make the array only 1 and 2arr = [1, 2]
    
    • This is certainly unreasonable because it is not an array before changing
    • It's equivalent to the heart getting an array to the variable arr
    • It is equivalent to changing the address stored in the arr, that is, changing the storage space instead of modifying it in the previous space
    • So we need some methods to change the data in the storage space without changing the storage space

push of common array methods

  • push is used to append an element to the end of the array

    var arr = [1, 2, 3]// Use the push method to append an element at the end of arr.push (4) console log(arr) // [1, 2, 3, 4]
    

pop of common array methods

  • pop is used to delete an element at the end of an array

    var arr = [1, 2, 3]// Use the pop method to delete the last element arr. Pop () console log(arr) // [1, 2]
    

unshift of common array methods

  • unshift adds an element to the front of the array

    var arr = [1, 2, 3]// Use the unshift method to add an element arr.unshift (4) console. To the front of the array log(arr) // [4, 1, 2, 3]
    

shift of common array methods

  • shift is to delete the first element of the array

    var arr = [1, 2, 3]// Use the shift method to delete the first element of the array, arr.shift () console log(arr) // [2, 3]
    

splice of common array methods

  • Slice is to intercept some contents of the array according to the index of the array

  • Syntax: splice (which index position to start from, how many to intercept, and new elements to replace) (the third parameter can not be written)

    var arr = [1, 2, 3, 4, 5]// Use the splice method to intercept the array arr.splice (1, 2) console log(arr) // [1, 4, 5]
    
    • arr.splice(1, 2) indicates that two contents are intercepted from index 1
    • The third parameter is not written, that is, there is no new content to replace the interception position
    var arr = [1, 2, 3, 4, 5]// Use the splice method to intercept the array arr.splice(1, 2, 'I'm new content') console Log (ARR) / / [1, 'I'm new', 4, 5]
    
    • arr.splice(1, 2, 'I'm new content') indicates that two contents are intercepted from index 1
    • Then fill the empty position with the third parameter

reverse of common array methods

  • Reverse is used to reverse the use of arrays

    var arr = [1, 2, 3]// Use the reverse method to reverse the array arr.reverse() console log(arr) // [3, 2, 1]
    

sort of common array methods

  • Sort is used to sort arrays

    var arr = [2, 3, 1]// Use the sort method to sort the array. Arr. Sort () console log(arr) // [1, 2, 3]
    
    • This is just a basic simple usage

concat of common array methods

  • concat is to splice multiple arrays

  • Unlike the previous method, concat does not change the original array, but returns a new array

    var arr = [1, 2, 3]// Use the concat method to splice the array var newarr = arr.concat ([4, 5, 6]) console log(arr) // [1, 2, 3]console. log(newArr) // [1, 2, 3, 4, 5, 6]
    
    • Note: the concat method does not change the original array

join of common array methods

  • join is to link each item in the array into a string

  • You can define the content join of each item by yourself

  • Instead of changing the original array, the linked string is returned

    var arr = [1, 2, 3]// Use join to link array var STR = arr.join ('-') console log(arr) // [1, 2, 3]console. log(str) // 1-2-3
    
    • Note: the join method does not change the original array, but returns a linked string

For and for in loops

  • Because the index of the array can get the contents of the array

  • The indexes of the array are arranged in the order of 0 ~ n

  • We can use the for loop to loop the array, because we can also set the for loop to increase in the order of 0 ~ n

  • We call this behavior ergodic

    var arr = [1, 2, 3, 4, 5]// Use the for loop to traverse the array for (VaR I = 0; I < arr.length; I + +) {console.log (arr [i])} / / 1, 2, 3, 4 and 5 will be printed on the console in turn
    
    • I < arr.length because length is the length of the array, which is a number, we can directly use it to determine the number of cycles
    • console.log(arr[i]) because with the loop, the value of I will increase from 0
    • So we are actually printing arr[0] / arr[1] /
  • Because the object has no index, we can't use the for loop to traverse

  • Here we use the for in loop to traverse the object

  • Let's start with a piece of code

    var obj = {  name: 'Jack',  age: 18}for (var key in obj) {  console.log(key)}// The content will be printed twice on the console, namely name and age
    
    • The traversal of the for in loop is determined by the number of members in the object
    • The number of members will be executed as many times as possible
    • key is a variable defined by ourselves, which is the same as i defined in the for loop
    • During each cycle, the key represents the attribute name of a member in the object

Sorting of arrays

  • Sorting is to turn an out of order array into an ordered array through our processing
  • Today, we will explain two ways to sort an array, bubble sort and selective sort

Bubble sorting

  • First traverse the array and compare the two next to each other. If the former is larger than the latter, change the two positions

  • After traversing the array, the last number is the largest one

  • Then perform the second traversal. According to the previous rules, the second largest number will run to the penultimate position

  • And so on, and finally the array will be arranged in order

    1. Let's prepare an out of order array first

      var arr = [3, 1, 5, 6, 4, 9, 7, 2, 8]
      
      • Next, we'll use code to sort the array
    2. Don't worry about looping. Let's look at the contents of the array and change the position

      // Suppose I want to change the positions of item 0 and item 1 in the array. / / I need to use the third variable var tmp = arr[0]arr[0] = arr[1]arr[1] = tmp
      
    3. Traverse the array for the first time and put the largest one at the end

      for (var i = 0; i < arr.length; i++) {  // Judge that if the current one in the array is larger than the latter one, the two exchange positions if (arr [i] > arr [i + 1]) {var TMP = arr [i] arr [i] = arr [i + 1] arr [i + 1] = TMP} / / after traversal, the array will become [3, 1, 5, 6, 4, 7, 2, 8, 9]
      
      • After the first time, the last one in the array will be the largest number
      • Then we execute the above code many times. The array is executed as many times as there are items
    4. How many times is the length of the array traversed

      for (var j = 0; j < arr.length; j++) {  for (var i = 0; i < arr.length; i++) {    // Judge that if the current one in the array is larger than the latter one, the two exchange positions if (arr [i] > arr [i + 1]) {var TMP = arr [i] arr [i] = arr [i + 1] arr [i + 1] = TMP}} / / after the end, the array will be sorted
      
    5. Give some optimization

      • Imagine a problem, assuming that the length of the array is 9, after the eighth row

      • The last eight numbers have been arranged in order, and the smallest one must be at the top

      • Then the ninth time is meaningless, because the smallest one is already in the front, and there will be no change of position

      • Then we don't need the ninth traversal, so we can reduce it once

        for (var j = 0; j < arr.length - 1; j++) {  for (var i = 0; i < arr.length; i++) {    // Judge that if the current one in the array is larger than the latter one, the two exchange positions if (arr [i] > arr [i + 1]) {var TMP = arr [i] arr [i] = arr [i + 1] arr [i + 1] = TMP}}}
        
      • The second question, the first time, has put the largest number at the end

      • Then the second time, in fact, there is no need to compare the penultimate one with the last one

      • Because we just want to put the second from the bottom in the second from the bottom. Even if we compare, we won't change the position

      • The third time, we have to count down the third number, so we don't have to compare it with the last two

      • And so on, in fact, each time you traverse, you traverse the current number - 1 times

        for (var j = 0; j < arr.length - 1; j++) {  for (var i = 0; i < arr.length - 1 - j; i++) {    // Judge that if the current one in the array is larger than the latter one, the two exchange positions if (arr [i] > arr [i + 1]) {var TMP = arr [i] arr [i] = arr [i + 1] arr [i + 1] = TMP}}}
        
    6. At this point, a bubble sort is completed

Select sort

  • Let's assume that the zero in the array is the index of the smallest number

  • Then traverse the array and replace the index of the previous record as long as there is a number smaller than me

  • After the array traversal is completed, you can find the smallest index, and then change the smallest index to the position of 0

  • Let's go through the second iteration, assuming that the first is the index of the smallest number

  • After traversing the array once, find the index of the number smaller than me

  • Change position after traversal

  • By analogy, you can also sort the array

    1. Prepare an array

      var arr = [3, 1, 5, 6, 4, 9, 7, 2, 8]
      
    2. Assume that the 0 th in the array is the index of the smallest number

      var minIndex = 0
      
    3. Traverse the array and judge that as long as the number is smaller than me, the index of the original record will be replaced

      var minIndex = 0for (var i = 0; i < arr.length; i++) {  if (arr[i] < arr[minIndex]) {    minIndex = i  }}// Find the smallest index after traversal. / / exchange the minIndex and the 0. var tmp = arr[minIndex]arr[minIndex] = arr[0]arr[0] = tmp
      
    4. Repeat the above code according to the length of the array

      for (var j = 0; j < arr.length; j++) {  // Because the first pass assumes the 0 and the second pass assumes the 1 / /, we need to assume the J. var minIndex = j / / because the smallest one has been put in the front, In the next cycle, you don't need to judge the previous one. / / you start from j + 1 directly. For (VaR I = j + 1; I < arr.length; I + +) {if (arr [i] < arr [minindex]) {minindex = I}}. / / after traversal, you find the smallest index. / / you exchange with the 0 in the first session, The second time is to exchange with the first / / we can exchange with the j directly. Var TMP = arr [minindex] arr [minindex] = arr [J] arr [J] = TMP}
      
    5. Some optimization

      • As before, after the penultimate sorting, it has been arranged. The last time is not necessary

        for (var j = 0; j < arr.length - 1; j++) {  var minIndex = j    for (var i = j + 1; i < arr.length; i++) {    if (arr[i] < arr[minIndex]) {      minIndex = i    }  }  var tmp = arr[minIndex]  arr[minIndex] = arr[j]  arr[j] = tmp}
        
      • Before exchanging variables, you can judge if the index obtained after traversal is consistent with the current index

      • Then it proves that the current one is the smallest one, so there is no need to exchange

      • When we make a judgment, we can only exchange when the minimum citation is different from the current citation

        for (var j = 0; j < arr.length - 1; j++) {  var minIndex = j    for (var i = j + 1; i < arr.length; i++) {    if (arr[i] < arr[minIndex]) {      minIndex = i    }  }  if (minIndex !== j) {    var tmp = arr[minIndex]    arr[minIndex] = arr[j]    arr[j] = tmp     }}
        
    6. At this point, the selection sorting is complete

ES5/String

Strict mode (understand)

  • We all know that js is a relatively loose language
  • And when developing, some codes are not very strict
  • The strict mode is to make requirements for some contents written during development

Turn on strict mode

  • To enable strict mode, write the string use strict directly at the beginning of the code

    <script>
    	'use strtic'
    	// The following code should be written in strict mode
    </script>
    

Strict pattern rules

  1. Declared variables must have var keyword

    'use strtic'
    
    var num = 100
    num2 = 200 // This will report an error
    
    • As I learned before, when declaring variables, if there is no var keyword, they will be automatically defined as global variables according to the scope rules
    • It is not allowed in strict mode, and an error will be reported
  2. The line parameters of the function cannot be repeated

    'use strtic'
    
    function fn(p1, p1) {} // An error will be reported directly
    
    • In the non strict mode, the two line parameters of the function are the same and will not report an error, but it is equivalent to only one variable inside the function
    • However, an error will be reported in strict mode
  3. When a declarative function is called, there is no this inside the function

    'use strtic'
    
    function fn() {
      console.log(this) // undefined
    }
    fn()
    
    • When a global declarative function is called, this inside the function points to window
    • In strict mode, there is no this

Common array methods in ES5

  • The common array methods we talked about before are ES3 methods
  • Today, let's talk about some methods in ES5

indexOf

  • indexOf is used to find the index of an item in the array

  • Syntax: indexof (the item in the array you are looking for)

    var arr = [1, 2, 3, 4, 5]
    
    // Use indexOf to find an item in the array
    var index = arr.indexOf(3)
    
    console.log(index) // 2
    
    • We're looking for the item with a value of 3 in the array
    • Returns the index of the item with value 3 in the array
  • If the content you are looking for is not in the array, it will return - 1

    var arr = [1, 2, 3, 4, 5]
    
    // Use indexOf to find an item in the array
    var index = arr.indexOf(10)
    
    console.log(index) // -1
    
    • If the value you are looking for does not exist in the array, it will return - 1

forEach

  • And the for loop are used to traverse the array

  • Syntax: arr.forEach(function (item, index, arr) {})

    var arr = [1, 2, 3]
    
    // Use forEach to traverse the array
    arr.forEach(function (item, index, arr) {
      // Item is each item in the array
      // Index is the index of the array
      // arr is the original array
      console.log('The second of the array ' + index + ' The value of the item is ' + item + ',The original array is', arr)
    })
    
    • The function passed during forEach() will be executed according to the length of the array
    • This function will execute as many times as the length of the array is

map

  • It is similar to forEach, except that you can operate on each item in the array and return a new array

    var arr = [1, 2, 3]
    
    // Traversing arrays using map
    var newArr = arr.map(function (item, index, arr) {
      // Item is each item in the array
      // Index is the index of the array
      // arr is the original array
      return item + 10
    })
    
    console.log(newArr) // [11, 12, 13]
    

filter

  • Similar to the use of map, we filter the array according to our criteria

  • Filter out those that meet the conditions in the original array and form a new array to return

    var arr = [1, 2, 3]// Use filter to filter the array var newarr = arr.filter (function (item, index, ARR) {/ / item is each item in the array / / index is the index of the array / / arr is the original array return item > 1}) console log(newArr) // [2, 3]
    
    • The condition we set is > 1
    • The new array returned will be all items > 1 in the original array

Create string (understand)

  • We also create strings in two ways: literal and constructor

  • Literal:

    var str = 'hello'
    
  • Constructor creation

    var str = new String('hello')
    

ASCII character set (understand)

  • As we all know, computers can only store binary numbers such as 0101010
  • Then our a ~ z / A ~ Z / $/ @ /... And other contents are also composed of binary numbers
  • We can simply understand that a ~ z / A ~ Z / $/ @ /... And other contents have their own numbers, and then these numbers are stored when stored in the computer. When we look at them, they are also parsed into the contents we want to see for us to see
  • [external link picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-bLwm7iql-1626013036398)(C:/Users / simple point / Desktop / profile / assets/ASCII control character. png)]
  • [the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-TqB6CkMc-1626013036399)(C:/Users / simple point / Desktop / profile / assets/ASCII display character. png)]
  • The above is the ASCII cross reference table. We just need to know how it is stored

unicode encoding

  • As we can see, ASCII has only this 128 character encoding structure
  • But because ASCII appeared earlier and was invented in the United States, these contents were enough in the early days
  • Because it is enough to store some English content and deliver some English articles
  • Then it must not be enough for the world
  • Because our Chinese characters cannot be stored, including the languages of some other countries
  • So there is unicode code, also known as (universal code, unified code)
  • The unicode cross reference table is the same as the ASCII cross reference table, but it becomes very large because it stores a lot of content
  • It also contains the text of most countries in the world, so our text and characters are now stored by converting them into numbers according to unicode coding
  • Our UTF-8 is an 8-bit unicode character set

Common methods of string

  • We manipulate strings and have a bunch of methods to help us operate
  • Strings and arrays have one thing in common and are arranged by index

charAt

  • Charat (index) is the content returned by finding the specified index position in the string

    var str = 'Jack'// Use charAt to find something in the string. Var index = str.charAt (2) console log(index) // c
    
    • Because strings are also arranged by index, starting from 0
    • So the location of index 2 is c
  • If there is no corresponding index, an empty string is returned

    var str = 'Jack'// Use charAt to find something in the string. Var index = str.charAt (10) console log(index) // ''
    
    • This string has no index 10 at all
    • So an empty string '' will be returned

charCodeAt

  • Charcodeat (index) is the unicode code that returns the corresponding index position

    var str = 'Jack'// Use charAt to find something in the string. Var index = str.charcodeat (0) console log(index) // 74
    
    • Because J stores 74 in the unicode cross reference table, it will return 74

indexOf

  • indexOf is to find the corresponding index according to characters

    var str = 'Jack'// Use indexOf to find the corresponding index var index = str.indexOf ('j ') console log(index) // 0
    
    • Because the index position of character J in string Jack is 0
    • So it will return 0

substring

  • substring is used to intercept strings

  • Syntax: substring (which index starts from and ends at), including the start index and not the end index

    var str = 'hello'//         01234 / / use substring to intercept the string var newstr = str.substring (1, 3) console log(newStr) // el
    
    • Starting from index 1 and ending at index 3, including the previous index and excluding the subsequent index
    • So the return is el

substr

  • substr is also used to intercept strings

  • Syntax: substr (which index to start from and how many to intercept)

    var str = 'hello'//         01234 / / use substr to intercept the string var newstr = str.substr (1, 3) console log(newStr) // ell
    
    • The difference between this method and substring is that the second parameter is how many to intercept
    • Starting from index 1, intercept 3, so you get ell

Tolower case and toUpperCase

  • These two methods use the to convert a string to lowercase and uppercase letters, respectively

    var str = hello// Use toUpperCase to convert to uppercase var upper = str.toUpperCase() console Log (upper) / / hello / / use tolowercase to convert to lowercase var lower = upper toLowerCase()console. log(lower) // hello
    

Math and Date

  • Math is a built-in object of js, which provides a bunch of methods to help us manipulate numbers
  • Date is a built-in object of js, which provides a bunch of methods to help us operate time

Math

  • There is nothing superfluous, just a bunch of methods to manipulate numbers

random

  • Math.random() is used to generate a random number between 0 and 1

  • The number generated by each execution is different, but it must be between 0 and 1

  • The generated number contains 0, but does not contain 1

    var num = Math.random()
    console.log(num) // Get a random number
    

round

  • Math.round() rounds a decimal number to an integer

    var num = 10.1
    console.log(Math.round(num)) // 10
    
    var num2 = 10.6
    console.log(Math.round(num2)) // 11
    

abs

  • Math.abs() is the absolute value that returns a number

    var num = -10
    console.log(math.abs(num)) // 10
    

ceil

  • Math.ceil() is an integer obtained by rounding up a decimal

    var num = 10.1
    console.log(Math.ceil(num)) // 11
    
    var num2 = 10.9
    console.log(Math.ceil(num2)) // 11
    

floor

  • Math.floor() is an integer that rounds a decimal down to

    var num = 10.1
    console.log(Math.floor(num)) // 10
    
    var num2 = 10.9
    console.log(Math.floor(num2)) // 10
    

max

  • Math.max() gets the largest of the numbers you pass in

    console.log(Math.max(1, 2, 3, 4, 5)) // 5
    

min

  • Math.min() gets the smallest of the numbers you pass in

    console.log(Math.min(1, 2, 3, 4, 5)) // 1
    

PI

  • Math.PI gets the value of π, which is 3.1415936

    console.log(Math.PI) // 3.141592653589793
    
    • Because of the calculation accuracy of the computer, only 15 decimal places can be obtained
    • Using math There is no need to add () to PI

Digital conversion base

  1. The toString() method can give a hexadecimal number when a number is converted to a string

    • Syntax: toString (base number you want to convert)

      var num = 100console.log(num.toString(2)) // 1100100console.log(num.toString(8)) // 144console.log(num.toString(16)) // 64
      
  2. The parseInt() method can convert the string into decimal as decimal when it is converted into a number

    • Syntax: parseInt (string to be converted, converted as decimal)

      var str = 100console.log(parseInt(str, 8)) // 64 the console obtained by converting 100 as an octal number into decimal Log (parseInt (STR, 16)) / / 256 convert 100 as a hexadecimal number into a decimal console Log (parseInt (STR, 2)) / / 4 it is obtained after converting 100 as a binary number into decimal
      

Date

  • The built-in constructor provided by js is specially used to obtain the time

new Date()

  • new Date() returns the current time by default without passing parameters

    var time = new Date()console.log(time) // Current time Fri Mar 01 2019 13:11:23 GMT+0800 (China standard time)
    
  • When new Date() passes in the parameter, you can get the time you passed in

    var time = new Date('2019-03-03 13:11:11')console.log(time) // Sun Mar 03 2019 13:11:11 GMT+0800 (China standard time)
    
  • The parameters passed by new Date() can be used in many cases

    1. Pass two numbers. The first represents the year and the second represents the month

      var time = new Date(2019, 00) // Months are counted from 0. 0 means January and 11 means December Log (time) / / Tue Jan 01 2019 00:00:00 GMT + 0800 (China standard time)
      
    2. Pass three numbers. The first two remain unchanged. The third represents the day of the month, from 1 to 31

      var time = new Date(2019, 00, 05) console.log(time) // Sat Jan 05 2019 00:00:00 GMT+0800 (China standard time)
      
    3. Pass four numbers. The first three remain unchanged. The fourth represents the time of the day, from 0 to 23

      var time = new Date(2019, 00, 05, 22) console.log(time) // Sat Jan 05 2019 22:00:00 GMT+0800 (China standard time)
      
    4. Pass five numbers. The first four remain unchanged. The fifth represents the number of minutes of the hour, from 0 to 59

      var time = new Date(2019, 00, 05, 22, 33) console.log(time) // Sat Jan 05 2019 22:33:00 GMT+0800 (China standard time)
      
    5. Pass six numbers, the first five unchanged, and the sixth represents the seconds of the minute, from 0 to 59

      var time = new Date(2019, 00, 05, 22, 33, 55) console.log(time) // Sat Jan 05 2019 22:33:55 GMT+0800 (China standard time)
      
    6. The form of the incoming string

      console.log(new Date('2019')) // Tue Jan 01 2019 08:00:00 GMT+0800 (China standard time) console Log (new date ('2019-02 ') / / fri Feb 01 2019 08:00:00 GMT + 0800 (China standard time) console Log (new date ('2019-02-03 ') / / Sun Feb 03 2019 08:00:00 GMT + 0800 (China standard time) console Log (new date ('2019-02-03 13: ') / / Sun Feb 03 2019 13:00:00 GMT + 0800 (China standard time) console Log (new date ('2019-02-03 13:13: ') / / Sun Feb 03 2019 13:13:00 GMT + 0800 (China standard time) console Log (new date ('2019-02-03 13:13:13 ') / / Sun Feb 03 2019 13:13:13 GMT + 0800 (China standard time)
      

Format the date string to the specified content

  • For example, the time string we get is Sun Feb 03 2019 13:13:13 GMT+0800 (China standard time)
  • I point to the year in this date. We need to get it in the form of intercepted string
  • But now js provides us with a series of methods to get the specified content

getFullYear

  • getFullYear() gets the year in the specified string

    var time = new Date(2019, 03, 03, 08, 00, 22)console.log(time.getFullYear()) // 2019
    

getMonth

  • The getMonth() method gets the month in the specified string

    var time = new Date(2019, 03, 03, 08, 00, 22)console.log(time.getMonth()) // 3
    
    • Here is a place to pay attention to
    • Months are counted from 0
    • 0 means January, 1 means February, and so on

getDate

  • The getDate() method gets the date in the specified string

    var time = new Date(2019, 03, 03, 08, 00, 22)console.log(time.getDate()) // 3
    

getHours

  • The getHours() method gets the hour in the specified string

    var time = new Date(2019, 03, 03, 08, 00, 22)console.log(time.getHours()) // 8
    

getMinutes

  • The getMinutes() method gets the minutes in the specified string

    var time = new Date(2019, 03, 03, 08, 00, 22)console.log(time.getMinutes()) // 0
    

getSeconds

  • The getSeconds() method gets the second in the specified string

    var time = new Date(2019, 03, 03, 08, 00, 22)console.log(time.getSeconds()) // 22
    

getDay

  • The getDay() method gets the specified string. The current date is the day of the week (Sunday is 0 and Saturday is 6)

    var time = new Date(2019, 03, 08, 08, 00, 22)console.log(time.getDay()) // 1
    

getTime

  • The getTime() method gets the number of milliseconds from the execution time to Greenwich mean time

    var time = new Date(2019, 03, 08, 08, 00, 22)console.log(time.getTime()) // 1554681622000
    

Get time difference

  • It refers to the time difference between two time points
  • You can't use time to subtract directly in js
  • We need some special operations
  • In the programming world, there is a special time, which is 00:00:00 on January 1, 1970
  • This time is called Greenwich mean time
  • In all programming worlds, this time is the same, and the number of Greenwich mean time is 0
  • Starting from Greenwich mean time, the number will + 1 every millisecond
  • So we can get the number of milliseconds from any time node to Greenwich mean time
  • Then, by subtracting two milliseconds, we can get the number of milliseconds difference between the two time points
  • We're getting the exact time from this millisecond

Calculate time difference

  • For example, let's calculate the time difference from 00:00:00 of 2019-01-01 to 04:55:34 of 2019-01-03
  1. First get the number of milliseconds from two time points to Greenwich mean time

    var time1 = new Date('2019-01-01 00:00:00')var time2 = new Date('2019-01-03 04:55:34')time1 = time1.getTime()time2 = time2.getTime()console.log(time1) // 1546272000000console.log(time2) // 1546462534000
    
  2. Subtract the two times to get the milliseconds difference between the two time points

    var differenceTime = time2 - time1console.log(differenceTime) // 190534000
    
    • Now we calculate the number of milliseconds between the two time points
  3. Convert the milliseconds we calculated into time

    • First calculate the number of days

    • Think a day is 1000 * 60 * 60 * 24 milliseconds

    • Divide the total number of milliseconds by the number of milliseconds in a day to get the number of days

      var time1 = new Date('2019-01-01 00:00:00')var time2 = new Date('2019-01-03 04:55:34')time1 = time1.getTime()time2 = time2.getTime()var differenceTime = time2 - time1// Calculate the whole number of days var day = differencetime / (1000 * 60 * 60 * 24) / / 2.205254629963 day = math ceil(day) // 2
      
      • Because we get the number of decimal days, we round down to get the number of integer days
    • Use differenceTime to subtract the number of milliseconds in two days, and the rest is the number of milliseconds in less than one day

    • Calculate the number of hours in milliseconds less than a day

    • Because an hour is 1000 * 60 * 60 milliseconds

    • Divide the number of milliseconds in less than a day by the number of milliseconds in an hour to get the number of hours

      var time1 = new Date('2019-01-01 00:00:00')var time2 = new Date('2019-01-03 04:55:34')time1 = time1.getTime()time2 = time2.getTime()var differenceTime = time2 - time1// Calculate the whole number of days var day = differencetime / (1000 * 60 * 60 * 24) / / 2.205254629963 day = math Floor (day) / / 2 / / calculate the whole hours var afterhours = differencetime - (1000 * 60 * 60 * 24 * 2) var hours = afterhours / (1000 * 60 * 60) hours = math floor(hours) // 4
      
      • As just now, we need to round down
    • Similarly, use afterhours - the number of milliseconds contained in 4 hours, and the rest is the number of milliseconds less than one hour

    • Calculate the number of minutes in milliseconds less than an hour

    • Because one minute is 1000 * 60 milliseconds

    • Divide the number of milliseconds in less than an hour by the number of milliseconds in a minute to get the number of minutes

      var time1 = new Date('2019-01-01 00:00:00')var time2 = new Date('2019-01-03 04:55:34')time1 = time1.getTime()time2 = time2.getTime()var differenceTime = time2 - time1// Calculate the whole number of days var day = differencetime / (1000 * 60 * 60 * 24) / / 2.205254629963 day = math Floor (day) / / 2 / / calculate the whole hours var afterhours = differencetime - (1000 * 60 * 60 * 24 * 2) var hours = afterhours / (1000 * 60 * 60) hours = math Floor (hours) / / 4 / / calculate the whole minutes var afterminutes = afterhours - (1000 * 60 * 60 * 4) var minutes = afterminutes / (1000 * 60) minutes = math floor(minutes) // 55
      
    • Calculate the second in the same way as before

      var time1 = new Date('2019-01-01 00:00:00')var time2 = new Date('2019-01-03 04:55:34')time1 = time1.getTime()time2 = time2.getTime()var differenceTime = time2 - time1// Calculate the whole number of days var day = differencetime / (1000 * 60 * 60 * 24) / / 2.205254629963 day = math Floor (day) / / 2 / / calculate the whole hours var afterhours = differencetime - (1000 * 60 * 60 * 24 * 2) var hours = afterhours / (1000 * 60 * 60) hours = math Floor (hours) / / 4 / / calculate the whole minutes var afterminutes = afterhours - (1000 * 60 * 60 * 4) var minutes = afterminutes / (1000 * 60) minutes = math Floor (minutes) / / 55 / / calculate the whole seconds var Afterseconds = afterminutes - (1000 * 60 * 55) var seconds = Afterseconds / 1000seconds = math floor(seconds) // 34
      
    • Finally, similarly, subtract the number of whole seconds, and the rest is the number of milliseconds

      var time1 = new Date('2019-01-01 00:00:00')var time2 = new Date('2019-01-03 04:55:34')time1 = time1.getTime()time2 = time2.getTime()var differenceTime = time2 - time1// Calculate the whole number of days var day = differencetime / (1000 * 60 * 60 * 24) / / 2.205254629963 day = math Floor (day) / / 2 / / calculate the whole hours var afterhours = differencetime - (1000 * 60 * 60 * 24 * 2) var hours = afterhours / (1000 * 60 * 60) hours = math Floor (hours) / / 4 / / calculate the whole minutes var afterminutes = afterhours - (1000 * 60 * 60 * 4) var minutes = afterminutes / (1000 * 60) minutes = math Floor (minutes) / / 55 / / calculate the whole seconds var Afterseconds = afterminutes - (1000 * 60 * 55) var seconds = Afterseconds / 1000seconds = math Floor (seconds) / / 34 / / calculate the number of milliseconds var milliSeconds = afterSeconds - (1000 * 34) // 0
      
    • Finally, we can output the results

      document.write('2019-01-01 00:00:00 And 2019-01-03 04:55:34 Difference between')document.write(day + 'day' + hours + 'hour' + minutes + 'minute' + seconds + 'second' + milliSeconds + 'millisecond')
      

BOM and DOM (upper)

  • Today, we start using js to manipulate html elements in browsers and pages

BOM

  • BOM (browser object model): Browser Object Model
  • In fact, it is some ability to operate the browser
  • What can we do
    • Get some browser related information (window size)
    • Operate the browser for page Jump
    • Gets information about the current browser address bar
    • Operate the scroll bar of the browser
    • Browser information (browser version)
    • Let the browser display a pop-up box (alert / confirm / prompt)
    • ...
  • The core of BOM is window object
  • window is a built-in object of the browser, which contains the methods of operating the browser

Gets the size of the browser window

  • innerHeight and innerWidth

  • These two methods are used to obtain the width and height of the browser window (including the scroll bar)

    var windowHeight = window.innerHeight
    console.log(windowHeight)
    
    var windowWidth = window.innerWidth
    console.log(windowWidth)
    

Browser pop-up layer

  • alert is a pop-up prompt box in the browser

    window.alert('I am a prompt box')
    

    [the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-YBkW7MR5-1626013036400)(C:/Users / simple point / Desktop / profile / assets/alert.png)]

    • The pop-up layer has a prompt content and only an OK button
    • After clicking the OK button, the prompt box disappears
  • confirm is to pop up a query box in the browser

    var boo = window.confirm('I am a question box')
    console.log(boo)
    

    [the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (IMG vkiaarqs-1626013036401) (C: / users / simple point / Desktop / profile / assets/confirm.png)]

    • The pop-up layer has a query message and two buttons
    • When you click OK, you will get true
    • When you click Cancel, you will get false
  • prompt is an input box that pops up in the browser

    var str = window.prompt('Please enter the content')
    console.log(str)
    

    [the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-cWbuxnDY-1626013036402)(C:/Users / simple point / Desktop / profile / assets/prompt.png)]

    • The pop-up layer has an input box and two buttons
    • When you click Cancel, you get null
    • When you click OK, you get the content you entered

Browser address information

  • There is an object called location in the window
  • It is specially used to store the information in the address bar of the browser

location.href

  • location.href this attribute stores the url address information in the browser address bar

    console.log(window.location.href)
    
    • It will change Chinese into url encoding format
  • location.href this attribute can also be assigned to it

    window.location.href = './index.html'
    // This page will jump to the address you gave later
    

location.reload

  • location. The reload () method will reload the page again, which is equivalent to refreshing

    window.location.reload()
    
    • Note: do not write in the global, otherwise the browser will always be in the refresh state

Browser history

  • There is an object called history in the window
  • It is specially used to store history information

history.back

  • history.back is used to return the history record, that is, to return to the previous page, which is equivalent to that on the browser ⬅️ Button

    window.history.back()
    
    • The premise is that you must have a previous record, or you will not go back even if you have been on this page

history.forword

  • history.forword is to go to the next historical record, that is, to the next page, which is equivalent to that on the browser ➡️ Button

    window.history.forward()
    
    • The premise is that you have had a fallback operation before, otherwise you are now the last page and there is no next page

Browser version information (understand)

  • There is an object in the window called navigator
  • It is specially used to obtain browser information

navigator.userAgent

  • navigator.userAgent is the overall information of the browser

    console.log(window.navigator.userAgent)// Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36
    

navigator.appName

  • navigator.appName gets the name of the browser

    console.log(window.navigator.appName)
    

navigator.appVersion

  • navigator.appVersion gets the version number of the browser

    console.log(window.navigator.appVersion)
    

navigator.platform

  • navigator.platform gets the operating system of the current computer

    console.log(window.navigator.platform)
    

onload event for browser

  • This is no longer an object, but an event

  • It is executed after all resources on the page are loaded

    window.onload = function () {  console.log('The page has been loaded')}
    

Write js in the head in the html page

<html>  <head>    <meta charset="UTF-8" />    <script>    	// When the code is executed, the body is not loaded. / / at this time, we can't get the div in the body. / / we need to use window Onload event window Onload = function() {/ / this function will be executed after the page is loaded. / / then the DOM elements of the page have been loaded, and we can get div} < / script > < / head > < body > < div > < / div ></body></html>

Write js at the end of the body in the html page

<html>  <head>    <meta charset="UTF-8" />  </head>  <body>    <div></div>    <script>    	// When this code is executed, the body has been loaded. / / you can get the div here. Do you want to write window Onload doesn't matter window Onload = function() {/ / this function will be executed after the page is loaded. / / then the DOM elements of the page have been loaded, and we can get the div} < / script ></body></html>

onscroll event for browser

  • This onscroll event is triggered when the browser's scroll bar scrolls

  • Or start when the mouse wheel rolls

    window.onscroll = function () {  console.log('The browser scrolled')}
    
    • Note: the premise is that the height of the page should exceed the window of the browser

Browser scrolling distance

  • The content in the browser can be scrolled, so we can get the scrolling distance of the browser
  • Think about a question?
    • Did the browser really scroll?
    • In fact, our browser doesn't scroll. It's always there
    • What is rolling? This is our page
    • So, in fact, the browser didn't move, but the page went up
  • Therefore, this is not simply the content of the browser, but the content of our page
  • So instead of using the window object, you are using the document object

scrollTop

  • Gets the distance the page scrolls up

  • There are two acquisition methods

    • document.body.scrollTop
    • document.documentElement.scrollTop
    window.onscroll = function () {  console.log(document.body.scrollTop)  console.log(document.documentElement.scrollTop)}
    
    • Both get the distance the page scrolls up
    • difference:
      • Internet Explorer
        • When there is no DOCTYPE declaration, use both of them
        • When there is a DOCTYPE declaration, you can only use document documentElement. scrollTop
      • Chrome and FireFox
        • When there is no DOCTYPE declaration, use document body. scrollTop
        • When there is a DOCTYPE declaration, use document documentElement. scrollTop
      • Safari
        • Do not use either. Use a separate method window pageYOffset

scrollLeft

  • Gets the distance the page scrolls to the left

  • There are also two ways

    • document.body.scrollLeft

    • document.documentElementLeft

      window.onscroll = function () {  console.log(document.body.scrollLeft)  console.log(document.documentElement.scrollLeft)}
      
    • The difference between the two is the same as the previous scrollTop

timer

  • In js, there are two kinds of timers, countdown timer and interval timer

Countdown timer

  • Count down how long it takes to execute the function

  • Syntax: setTimeout (function to be executed, how long will it be executed later)

  • The function will be executed after the time you set

    var timerId = setTimeout(function () {  console.log('I did')}, 1000)console.log(timerId) // 1
    
    • Time is calculated in milliseconds. 1000 milliseconds is 1 second
    • Therefore, the function will be executed 1 second after the page is opened
    • If you only execute it once, you won't execute it anymore
    • The return value is the number of timers in the current page

Interval timer

  • How often is the function executed

  • Syntax: setinterval (function to be executed, interval time)

    var timerId = setInterval(function () {  console.log('I did')}, 1000)
    
    • As before, the time is calculated in milliseconds
    • The function is executed every 1 second
    • As long as it is not closed, it will be executed all the time
    • The return value is the number of timers in the current page

Return value of timer

  • When setting the timer, its return value is part of setTimeout and setInterval

  • As long as there is a timer, it is a number

    var timerId = setTimeout(function () {  console.log('Countdown timer')}, 1000)var timerId2 = setInterval(function () {  console.log('Interval timer')}, 1000)console.log(timerId) // 1console.log(timerId2) // 2
    

off timer

  • We just mentioned a timer ID, which means that this timer is the first timer on the page

  • This timerId is the number used to turn off the timer

  • We have two ways to turn off the timers clearTimeout and clearInterval

    var timerId = setTimeout(function () {  console.log('Countdown timer')}, 1000)clearTimeout(timerId)
    
    • When off, the timer will not be running
    var timerId2 = setInterval(function () {  console.log('Interval timer')}, 1000)coearInterval(timerId2)
    
    • After shutdown, the timer will not execute
  • In principle

    • clearTimeout close setTimeout
    • clearInterval close setInterval
  • But in fact, they can be used in general. They can be mixed

    var timerId = setTimeout(function () {  console.log('Countdown timer')}, 1000)// Close the countdown timer clearinterval (timerid) var timerid2 = setinterval (function() {console. Log ('interval timer ')}, 1000) / / close the interval timer clearTimeout(timerId2)
    

DOM

  • DOM (document object model): Document Object Model
  • It's actually some ability to manipulate tags in html
  • What can we do
    • Get an element
    • Remove an element
    • Create an element
    • Add an element to the page
    • Bind some events to the element
    • Gets the properties of the element
    • Add some css styles to the element
    • ...
  • The core object of DOM is the docuemnt object
  • document object is a built-in object in the browser, which stores various methods specially used to operate elements
  • DOM: the tag in the page. After we get it through js, we will call this object DOM object

Get an element

  • Get the tags in the page through js code
  • After we get it, we can operate these tags

getElementById

  • getElementById gets the tag by its id name

  • Because the id is unique in a page, what you get is an element

    <body>  <div id="box"></div>  <script>  	var box = document.getElementById('box')  	console.log(box) // <div></div>  </script></body>
    
    • What you get is the div tag with id box in the page

getElementsByClassName

  • getElementsByClassName is the name of the class that used the tag to get the tag

  • Because the class names of multiple elements in the page may be the same, a group of elements is obtained

  • Even if you get only one class, you also get a group of elements, but there is only one DOM element in this group

    <body>  <div calss="box"></div>  <script>  	var box = document.getElementsByClassName('box')  	console.log(box) // [<div></div>]    console.log(box[0]) // <div></div>  </script></body>
    
    • What you get is a set of elements, a data structure that looks like an array, but it is not an array, but a pseudo array
    • This group of data is also arranged according to the index, so we need to use the index to get the div accurately

getElementsByTagName

  • getElementsByTagName is the name of the tag used to get the tag

  • Because the tag names of multiple elements in the page may be the same, a group of elements is obtained

  • Even if there is only one tag name, it is also a group of elements, but there is only one DOM element in this group

    <body>  <div></div>  <script>  	var box = document.getElementsByTagName('div')  	console.log(box) // [<div></div>]    console.log(box[0]) // <div></div>  </script></body>
    
    • Like getElementsByClassName, we get an element that looks like an array
    • You must use an index to get an accurate DOM element

querySelector

  • querySelector gets elements in the form of selectors

  • That is to say, it is obtained according to the selector when we write css

  • This method can only get one element, and it is the first element in the page that meets the condition

    console.log(document.querySelector('div')) // Get the first div element console. In the page Log (docuemnt. Queryselector ('. Box')) / / get the first element console with box class name in the page Log (document. Queryselector ('#box')) / / get the first element with id box in the page
    

querySelectorAll

  • querySelectorAll gets elements in the form of selectors

  • This method can get all the elements that meet the conditions and return them in the form of a pseudo array

    console.log(document.querySelectorAll('div')) // Get all the div elements in the page console Log (docuemnt. Queryselectorall ('. Box')) / / get all elements in the page with box class names
    
    • What you get is a set of data, and you also need to use the index to get each DOM element accurately

Operation properties

  • After we get the tags in the page through various ways of getting elements
  • We can directly manipulate the attributes of DOM elements and display the effect directly on the page

innerHTML

  • Gets the HTML structure inside the element

    <body>  <div>    <p>      <span>hello</span>    </p>  </div>  <script>    var div = document.querySelector('div')    console.log(div.innerHTML)      /*          <p>            <span>hello</span>          </p>	  */  </script></body>
    
  • Set the content of the element

    <body>  <div></div>  <script>    var div = document.querySelector('div')   	div.innerHTML = '<p>hello</p>'  </script></body>
    
    • After setting, a p element will be nested inside the div element in the page

innerText

  • Get the text inside the element (only the text content can be obtained, not the html tag)

    <body>  <div>    <p>      <span>hello</span>    </p>  </div>  <script>    var div = document.querySelector('div')    console.log(div.innerText) // hello  </script></body>
    
  • You can set the text inside the element

    <body>  <div></div>  <script>    var div = document.querySelector('div')   	div.innerText = '<p>hello</p>'  </script></body>
    
    • After setting, the < p > Hello < / P > will appear in the div element as a text instead of parsing P into a label

getAttribute

  • Get an attribute of an element (including custom attributes)

    <body>  <div a="100" class="box"></div>  <script>    var div = document.querySelector('div')   	console.log(div.getAttribute('a')) // 100    console.log(div.getAttribute('class')) // box  </script></body>
    

setAttribute

  • Set an attribute to the element (including custom attributes)

    <body>  <div></div>  <script>    var div = document.querySelector('div')   	div.setAttribute('a', 100)    div.setAttribute('class', 'box')    console.log(div) // <div a="100" class="box"></div>  </script></body>
    

removeAttribute

  • Directly remove an attribute of an element

    <body>  <div a="100" class="box"></div>  <script>    var div = document.querySelector('div')   	div.removeAttribute('class')    console.log(div) // <div a="100"></div>  </script></body>
    

style

  • Specifically used to add css styles to elements

  • All added are inline styles

    <body>  <div></div>  <script>    var div = document.querySelector('div')   	div.style.width = "100px"    div.style.height = "100px"    div.style.backgroundColor = "pink"    console.log(div)    // <div style="width: 100px; height: 100px; background-color: pink;"></div>  </script></body>
    
    • The div in the page will become a width and height of 100, and the background color is pink

className

  • The name of the class specifically used to manipulate the element

    <body>  <div class="box"></div>  <script>    var div = document.querySelector('div')   	console.log(div.className) // box  </script></body>
    
  • You can also set the class name of the element, but it is a full coverage operation

    <body>  <div class="box"></div>  <script>    var div = document.querySelector('div')   	div.className = 'test'    console.log(div) // <div class="test"></div>  </script></body>
    
    • When setting, whether there is a class name or not, it will be overwritten by the set value
  • DOM tree is composed of nodes in our html structure one by one

  • Not only is our label a node, but the text we write is also a node. Comments, including spaces, are nodes

DOM node

  • DOM nodes are generally divided into three categories: element nodes, text nodes and attribute nodes
  • What is classification? For example, when we get elements, we call them element nodes (tag nodes) through various methods
  • For example, the text written in our label is the text node
  • The attribute written on each label is the attribute node

Element node

  • We use getElementBy All obtained are element nodes

Attribute node

  • What we get through getAttribute is the attribute node of the element

Text node

  • What we get through innerText is the text node of the element

Get node

  • childNodes: get all child nodes under a node

    <body>
      <div>
        <p>hello</p>
      </div>
      
      <script>
        // This oDiv obtains the div element in the page, which is an element node
      	var oDiv = document.querySelector('div')
        
        console.log(oDiv.childNodes) 
        /*
        	NodeList(3) [text, p, text]
          0: text
          1: p
          2: text
          length: 3
          __proto__: NodeList
        */
      </script>
    </body>
    
    • We will find that after we get it, it is a pseudo array with three nodes
    • A text: from < div > to < p > there is a newline and a pile of spaces in the middle. This is the first node and a text node
    • A p: this p tag is the second node, and this is an element node
    • A text: from < / P > to < / div >, there is a newline and a pile of spaces in the middle. This is the third node and a text node
    • At this time, you can see that we have different node types
  • children: get all child element nodes under a node

    <body>
      <div>
        <p>hello</p>
      </div>
      
      <script>
        // This oDiv obtains the div element in the page, which is an element node
      	var oDiv = document.querySelector('div')
        
        console.log(oDiv.children) 
        /*
        	HTMLCollection [p]
          0: p
          length: 1
          __proto__: HTMLCollection
        */
      </script>
    </body>
    
    • We found that there is only one node, because children only need element nodes
    • There is only one element node under div, which is p
    • So there is only one, although there is only one, but it is also a pseudo array
  • firstChild: get the first node of the child level of a node

    <body>
      <div>
        <p>hello</p>
      </div>
      
      <script>
        // This oDiv obtains the div element in the page, which is an element node
      	var oDiv = document.querySelector('div')
        
        console.log(oDiv.firstChild) // #text 
      </script>
    </body>
    
    • This is to get only one node, which is no longer a pseudo array
    • Get the first one
    • The first is the newline and space from < div > to < p >, which is a text node
  • lastChild: get the last node of the child level of a node

    <body>
      <div>
        <p>hello</p>
      </div>
      
      <script>
        // This oDiv obtains the div element in the page, which is an element node
      	var oDiv = document.querySelector('div')
        
        console.log(oDiv.lastChild) // #text 
      </script>
    </body>
    
    • Get only one node, no longer a pseudo array
    • Get the last one
    • The last one is line breaks and spaces from < / P > to < / div >, which is a text node
  • firstElementChild: get the first element node of the child level of a node

    <body>
      <div>
        <p>hello</p>
      </div>
      
      <script>
        // This oDiv obtains the div element in the page, which is an element node
      	var oDiv = document.querySelector('div')
        
        console.log(oDiv.firstElementChild) // <p>hello</p>
      </script>
    </body>
    
    • Get only one node, not a pseudo array
    • Gets the first element node
    • The first element node is the p tag, which is an element node
  • lastElementChild: get the last element node of the child level of a node

    <body>
      <div>
        <p>hello</p>
        <p>world</p>
      </div>
      
      <script>
        // This oDiv obtains the div element in the page, which is an element node
      	var oDiv = document.querySelector('div')
        
        console.log(oDiv.lastElementChild) // <p>world</p>
      </script>
    </body>
    
    • Get only one node, not a pseudo array
    • Gets the last element node
    • The last element node is < p > World < / P >, which is an element node
  • nextSibling: get the next sibling node of a node

    <body>
      <ul>
        <li id="a">hello</li>
        <li id="b">world</li>
        <li id="c">!!!</li>
      </ul>
      
      <script>
        // This oLi obtains the li element in the page, which is an element node
      	var oLi = document.querySelector('#b')
        
        console.log(oLi.nextSibling) // #text
      </script>
    </body>
    
    • Get only one node, not a pseudo array
    • The next sibling node of the li with id="b" is obtained
    • Because the next node of id="b" is a line break and space between two li tags, it is a text node
  • previousSibling: get the previous sibling node of a node

    <body>
      <ul>
        <li id="a">hello</li>
        <li id="b">world</li>
        <li id="c">!!!</li>
      </ul>
      
      <script>
        // This oLi obtains the li element in the page, which is an element node
      	var oLi = document.querySelector('#b')
        
        console.log(oLi.previousSibling) // #text
      </script>
    </body>
    
    • Get only one node, not a pseudo array
    • The last sibling node of the li with id="b" is obtained
    • Because the previous node of id="b" is a line feed and space between two li tags, it is a text node
  • Nexterementsibling: get the next element node of a node

    <body>  <ul>    <li id="a">hello</li>    <li id="b">world</li>    <li id="c">!!!</li>  </ul>    <script>    // This oli obtains the Li element in the page, which is an element node 	 var oLi = document. querySelector('#b')        console. log(oLi.nextElementSibling) // <li id="c">!!!</ li>  </script></body>
    
    • Get only one node, not a pseudo array
    • The next sibling element node of the li with id="b" is obtained
    • Because the next sibling element node of id="b" is the li of id="c", which is an element node
  • previousElementSibling: get the previous element node of a node

    <body>  <ul>    <li id="a">hello</li>    <li id="b">world</li>    <li id="c">!!!</li>  </ul>    <script>    // This oli obtains the Li element in the page, which is an element node 	 var oLi = document. querySelector('#b')        console. log(oLi.previousElementSibling) // <li id="a">hello</li>  </script></body>
    
    • Get only one node, not a pseudo array
    • The last sibling element node of the li with id="b" is obtained
    • Because the last sibling element node of id="b" is the li of id="a", which is an element node
  • parentNode: get the parent node of a node

    <body>  <ul>    <li id="a">hello</li>    <li id="b">world</li>    <li id="c">!!!</li>  </ul>    <script>    // This oli obtains the li element in the page, which is an element node 	 var oLi = document. querySelector('#b')        console. log(oLi.parentNode) // <ul>...</ ul>  </script></body>
    
    • Get only one node, not a pseudo array
    • Gets the parent element node of the current li
    • Because the father of this li is ul, what you get is ul, which is an element node
  • attributes: get all attribute nodes of an element node

    <body>  <ul>    <li id="a" a="100" test="test">hello</li>  </ul>    <script>    // This oli obtains the li element in the page, which is an element node 	 var oLi = document.querySelector('#a')        console.log(oLi.attributes)     /*     	 NamedNodeMap {0: id, 1: a, 2: test, id: id, a: a, test: test, length: 3}      0: id      1: a      2: test      length: 3      a: a      id: id      test: test      __ proto__:  NamedNodeMap        */  </script></body>
    
    • What is obtained is a set of data, which is all the attributes of the element and a pseudo array
    • This li has three attributes, id / a / test, so we get these three attributes

Node attribute

  • We already know that nodes can be divided into many kinds, and we can also obtain various nodes

  • Next, let's talk about the differences of attributes between various nodes

  • Let's prepare a piece of code first

    <body>  <ul test="I am ul A property of">    <li>hello</li>  </ul>  <script>    // First get UL var oul = document Queryselector ('ul ') / / obtains the first child element node under UL, which is an element node var elenode = oul Firstelementchild / / get the attribute node combination of UL. Because it is a combination, we need to use the index var attrnode = oul Attributes [0] / / get the first child node under UL, which is a text node var textnode = oul firstChild  </script></body>
    

nodeType

  • nodeType: gets the node type of the node, expressed in numbers

    console.log(eleNode.nodeType) // 1console.log(attrNode.nodeType) // 2console.log(textNode.nodeType) // 3
    
    • nodeType === 1 indicates that the node is an element node
    • nodeType === 2 indicates that the node is an attribute node
    • nodeType === 3 indicates that the node is a comment node

nodeName

  • nodeName: gets the node name of the node

    console.log(eleNode.nodeName) // LIconsole.log(attrNode.nodeName) // testconsole.log(textNode.nodeName) // #text
    
    • The nodeName of the element node is the upper case label name
    • The nodeName of the attribute node is the attribute name
    • The nodeName of the text node is #text

nodeValue

  • nodeValue: gets the value of the node

    console.log(eleNode.nodeValue) // nullconsole.log(attrNode.nodeValue) / / I am an attribute of ul console Log (textnode. NodeValue) / / newline + space
    
    • Element node has no nodeValue
    • The nodeValue of the attribute node is the attribute value
    • The nodeValue of a text node is the text content

Summary

-nodeTypenodeNamenodeValue
Element node1Upper case label namenull
Attribute node2Attribute nameAttribute value
Text node3#textText content

Manipulating DOM nodes

  • The operation we are talking about is nothing more than adding, deleting, modifying and querying (CRUD)
  • Create a node (because we need to create a node before adding it to the page)
  • Add a node to the page
  • Delete a node in the page
  • Modify a node in the page
  • Get a node in the page

Create a node

  • createElement: used to create an element node

    // Create a div element node var odiv = document createElement('div')console. log(oDiv) // <div></div>
    
    • What is created is a div element that can be used
  • createTextNode: used to create a text node

    // Create a text node var otext = document CreateTextNode ('I am a text ') console Log (otext) / / "I am a text"
    

Add a node to the page

  • appendChild: appends a node to the end of an element node

  • Syntax: parent node AppendChild (child node to insert)

    // Create a div element node var odiv = document createElement('div')var oText = document. CreateTextNode ('I am a text ') / / append a text node odiv appendChild(oText)console. Log (odiv) / / < div > I am a text < / div >
    
  • insertBefore: inserts a node before a node

  • Syntax: parent node InsertBefore (the node to be inserted, in front of which node)

    <body>  <div>    <p>I am a p label</p>  </div>    <script>  	var oDiv = document.querySelector('div')    var oP = oDiv.querySelector('p')        // Create an element node var OSPAN = document CreateElement ('span ') / / add this element node to odiv before P under Div insertBefore(oSpan, oP)        console. log(oDiv)    /*     	< div>     		< span></span>     		< p> I am a p tag</p> 	</ div>    */  </script></body>
    

Delete a node in the page

  • removeChild: removes a node under a node

  • Syntax: parent node Removechild (byte point to be removed)

    <body>  <div>    <p>I am a p label</p>  </div>    <script>  	var oDiv = document.querySelector('div')    var oP = oDiv.querySelector('p')        // Remove the p tag odiv. Under Div removeChild(oP)        console. log(oDiv) // <div></div>  </script></body>
    

Modify a node in the page

  • replaceChild: replace a node in the page

  • Syntax: parent node Replacechild (new node, old node)

    <body>  <div>    <p>I am a p label</p>  </div>    <script>  	var oDiv = document.querySelector('div')    var oP = oDiv.querySelector('p')        // Create a span node var OSPAN = document CreateElement ('span ') / / add some text OSPAN to the span element InnerHTML = 'I am a newly created span tag' 	//  Replace the p label odiv under the original div with the created span label replaceChild(oSpan, oP)        console. log(oDiv)    /*     	< div>     		< Span > I am a newly created span tag</span> 	</ div>    */  </script></body>
    

Gets the non line style of the element

  • When we operate DOM, a very important point is to operate the css style of elements

  • When operating css style, we can't avoid getting the style of elements

  • As we said before, we can use elements style.xxx to get

  • However, this method can only get the element inter line style, that is, the style written in the line

    <style>  div {    width: 100px;  }</style><body>  <div style="height: 100px;">    <p>I am a p label</p>  </div>  <script>    var oDiv = document.querySelector('div')		console.log(oDiv.style.height) // 100px    console.log(oDIv.style.width) // ''  </script></body>
    
  • We can't get the style of this element whether it's external chained or embedded

  • Here we will use the method to get getComputedStyle and currentStyle

  • The functions of these two methods are the same, except one in non IE browser and one in IE browser

getComputedStyle (not used by IE)

  • Syntax: window Getcomputedstyle (element, null) Properties to get

    <style>  div {    width: 100px;  }</style><body>  <div style="height: 100px;">    <p>I am a p label</p>  </div>  <script>    var oDiv = document.querySelector('div')		console.log(window.getComputedStyle(oDiv).width) // 100px    console.log(window.getComputedStyle(oDiv).height) // 100px  </script></body>
    
    • This method can obtain both inter line style and non inter line style

currentStyle (used by IE)

  • Syntax: elements currentStyle. Properties to get

    <style>  div {    width: 100px;  }</style><body>  <div style="height: 100px;">    <p>I am a p label</p>  </div>  <script>    var oDiv = document.querySelector('div')		console.log(oDiv.currentStyle.width) // 100px    console.log(oDiv.currentStyle.height) // 100px  </script></body>
    

Gets the offset of the element

  • Is the distance of the element on the page relative to the left and top of the reference parent

offsetParent

  • Gets the offset reference parent of the element
  • In fact, suppose you want to give an element absolute positioning
  • According to whom is it located
  • Who is the offset reference parent of this element

offsetLeft and offsetTop

  • Get the offset on the left side of the element and the offset on the upper side
  • offsetLeft: the left offset of the element relative to the reference parent
  • offsetTop: the upper offset of the element relative to the reference parent

Get element size

  • Is to get the "floor area" of the element

offsetWith and offsetHeight

  • offsetWidth: get the width of element content + padding + border
  • offsetHeight: get the height of element content + padding + border

clientWidth and clientHeight

  • clientWidth: gets the width of element content + padding

  • clientHeight: get the height of element content + padding

be careful

  • The obtained dimension is a number without units
  • When the element does not occupy a position in the page, it gets 0
    • display: none; Element does not occupy a space on the page
    • visibility: hidden; Element occupying space on page

Get browser window size

  • We learned innerWidth and innerHeight before

  • What they get is the size of the window containing the scroll bar

  • Next, let's learn two ways to obtain the size without scroll bars

  • document.documentElement.clientWidth: the width of the visual window

  • document.documentElement.clientHeight: the height of the visual window

  • DOM tree is composed of nodes in our html structure one by one

  • Not only is our label a node, but the text we write is also a node. Comments, including spaces, are nodes

DOM node

  • DOM nodes are generally divided into three categories: element nodes, text nodes and attribute nodes
  • What is classification? For example, when we get elements, we call them element nodes (tag nodes) through various methods
  • For example, the text written in our label is the text node
  • The attribute written on each label is the attribute node

Element node

  • We use getElementBy All obtained are element nodes

Attribute node

  • What we get through getAttribute is the attribute node of the element

Text node

  • What we get through innerText is the text node of the element

Get node

  • childNodes: get all child nodes under a node

    <body>
      <div>
        <p>hello</p>
      </div>
      
      <script>
        // This oDiv obtains the div element in the page, which is an element node
      	var oDiv = document.querySelector('div')
        
        console.log(oDiv.childNodes) 
        /*
        	NodeList(3) [text, p, text]
          0: text
          1: p
          2: text
          length: 3
          __proto__: NodeList
        */
      </script>
    </body>
    
    • We will find that after we get it, it is a pseudo array with three nodes
    • A text: from < div > to < p > there is a newline and a pile of spaces in the middle. This is the first node and a text node
    • A p: this p tag is the second node, and this is an element node
    • A text: from < / P > to < / div >, there is a newline and a pile of spaces in the middle. This is the third node and a text node
    • At this time, you can see that we have different node types
  • children: get all child element nodes under a node

    <body>
      <div>
        <p>hello</p>
      </div>
      
      <script>
        // This oDiv obtains the div element in the page, which is an element node
      	var oDiv = document.querySelector('div')
        
        console.log(oDiv.children) 
        /*
        	HTMLCollection [p]
          0: p
          length: 1
          __proto__: HTMLCollection
        */
      </script>
    </body>
    
    • We found that there is only one node, because children only need element nodes
    • There is only one element node under div, which is p
    • So there is only one, although there is only one, but it is also a pseudo array
  • firstChild: get the first node of the child level of a node

    <body>
      <div>
        <p>hello</p>
      </div>
      
      <script>
        // This oDiv obtains the div element in the page, which is an element node
      	var oDiv = document.querySelector('div')
        
        console.log(oDiv.firstChild) // #text 
      </script>
    </body>
    
    • This is to get only one node, which is no longer a pseudo array
    • Get the first one
    • The first is the newline and space from < div > to < p >, which is a text node
  • lastChild: get the last node of the child level of a node

    <body>
      <div>
        <p>hello</p>
      </div>
      
      <script>
        // This oDiv obtains the div element in the page, which is an element node
      	var oDiv = document.querySelector('div')
        
        console.log(oDiv.lastChild) // #text 
      </script>
    </body>
    
    • Get only one node, no longer a pseudo array
    • Get the last one
    • The last one is line breaks and spaces from < / P > to < / div >, which is a text node
  • firstElementChild: get the first element node of the child level of a node

    <body>
      <div>
        <p>hello</p>
      </div>
      
      <script>
        // This oDiv obtains the div element in the page, which is an element node
      	var oDiv = document.querySelector('div')
        
        console.log(oDiv.firstElementChild) // <p>hello</p>
      </script>
    </body>
    
    • Get only one node, not a pseudo array
    • Gets the first element node
    • The first element node is the p tag, which is an element node
  • lastElementChild: get the last element node of the child level of a node

    <body>
      <div>
        <p>hello</p>
        <p>world</p>
      </div>
      
      <script>
        // This oDiv obtains the div element in the page, which is an element node
      	var oDiv = document.querySelector('div')
        
        console.log(oDiv.lastElementChild) // <p>world</p>
      </script>
    </body>
    
    • Get only one node, not a pseudo array
    • Gets the last element node
    • The last element node is < p > World < / P >, which is an element node
  • nextSibling: get the next sibling node of a node

    <body>
      <ul>
        <li id="a">hello</li>
        <li id="b">world</li>
        <li id="c">!!!</li>
      </ul>
      
      <script>
        // This oLi obtains the li element in the page, which is an element node
      	var oLi = document.querySelector('#b')
        
        console.log(oLi.nextSibling) // #text
      </script>
    </body>
    
    • Get only one node, not a pseudo array
    • The next sibling node of the li with id="b" is obtained
    • Because the next node of id="b" is a line break and space between two li tags, it is a text node
  • previousSibling: get the previous sibling node of a node

    <body>
      <ul>
        <li id="a">hello</li>
        <li id="b">world</li>
        <li id="c">!!!</li>
      </ul>
      
      <script>
        // This oLi obtains the li element in the page, which is an element node
      	var oLi = document.querySelector('#b')
        
        console.log(oLi.previousSibling) // #text
      </script>
    </body>
    
    • Get only one node, not a pseudo array
    • The last sibling node of the li with id="b" is obtained
    • Because the previous node of id="b" is a line feed and space between two li tags, it is a text node
  • Nexterementsibling: get the next element node of a node

    <body>  <ul>    <li id="a">hello</li>    <li id="b">world</li>    <li id="c">!!!</li>  </ul>    <script>    // This oli obtains the Li element in the page, which is an element node 	 var oLi = document. querySelector('#b')        console. log(oLi.nextElementSibling) // <li id="c">!!!</ li>  </script></body>
    
    • Get only one node, not a pseudo array
    • The next sibling element node of the li with id="b" is obtained
    • Because the next sibling element node of id="b" is the li of id="c", which is an element node
  • previousElementSibling: get the previous element node of a node

    <body>  <ul>    <li id="a">hello</li>    <li id="b">world</li>    <li id="c">!!!</li>  </ul>    <script>    // This oli obtains the Li element in the page, which is an element node 	 var oLi = document. querySelector('#b')        console. log(oLi.previousElementSibling) // <li id="a">hello</li>  </script></body>
    
    • Get only one node, not a pseudo array
    • The last sibling element node of the li with id="b" is obtained
    • Because the last sibling element node of id="b" is the li of id="a", which is an element node
  • parentNode: get the parent node of a node

    <body>  <ul>    <li id="a">hello</li>    <li id="b">world</li>    <li id="c">!!!</li>  </ul>    <script>    // This oli obtains the li element in the page, which is an element node 	 var oLi = document. querySelector('#b')        console. log(oLi.parentNode) // <ul>...</ ul>  </script></body>
    
    • Get only one node, not a pseudo array
    • Gets the parent element node of the current li
    • Because the father of this li is ul, what you get is ul, which is an element node
  • attributes: get all attribute nodes of an element node

    <body>  <ul>    <li id="a" a="100" test="test">hello</li>  </ul>    <script>    // This oli obtains the li element in the page, which is an element node 	 var oLi = document.querySelector('#a')        console.log(oLi.attributes)     /*     	 NamedNodeMap {0: id, 1: a, 2: test, id: id, a: a, test: test, length: 3}      0: id      1: a      2: test      length: 3      a: a      id: id      test: test      __ proto__:  NamedNodeMap        */  </script></body>
    
    • What is obtained is a set of data, which is all the attributes of the element and a pseudo array
    • This li has three attributes, id / a / test, so we get these three attributes

Node attribute

  • We already know that nodes can be divided into many kinds, and we can also obtain various nodes

  • Next, let's talk about the differences of attributes between various nodes

  • Let's prepare a piece of code first

    <body>  <ul test="I am ul A property of">    <li>hello</li>  </ul>  <script>    // First get UL var oul = document Queryselector ('ul ') / / obtains the first child element node under UL, which is an element node var elenode = oul Firstelementchild / / get the attribute node combination of UL. Because it is a combination, we need to use the index var attrnode = oul Attributes [0] / / get the first child node under UL, which is a text node var textnode = oul firstChild  </script></body>
    

nodeType

  • nodeType: gets the node type of the node, expressed in numbers

    console.log(eleNode.nodeType) // 1console.log(attrNode.nodeType) // 2console.log(textNode.nodeType) // 3
    
    • nodeType === 1 indicates that the node is an element node
    • nodeType === 2 indicates that the node is an attribute node
    • nodeType === 3 indicates that the node is a comment node

nodeName

  • nodeName: gets the node name of the node

    console.log(eleNode.nodeName) // LIconsole.log(attrNode.nodeName) // testconsole.log(textNode.nodeName) // #text
    
    • The nodeName of the element node is the upper case label name
    • The nodeName of the attribute node is the attribute name
    • The nodeName of the text node is #text

nodeValue

  • nodeValue: gets the value of the node

    console.log(eleNode.nodeValue) // nullconsole.log(attrNode.nodeValue) / / I am an attribute of ul console Log (textnode. NodeValue) / / newline + space
    
    • Element node has no nodeValue
    • The nodeValue of the attribute node is the attribute value
    • The nodeValue of a text node is the text content

Summary

-nodeTypenodeNamenodeValue
Element node1Upper case label namenull
Attribute node2Attribute nameAttribute value
Text node3#textText content

Manipulating DOM nodes

  • The operation we are talking about is nothing more than adding, deleting, modifying and querying (CRUD)
  • Create a node (because we need to create a node before adding it to the page)
  • Add a node to the page
  • Delete a node in the page
  • Modify a node in the page
  • Get a node in the page

Create a node

  • createElement: used to create an element node

    // Create a div element node var odiv = document createElement('div')console. log(oDiv) // <div></div>
    
    • What is created is a div element that can be used
  • createTextNode: used to create a text node

    // Create a text node var otext = document CreateTextNode ('I am a text ') console Log (otext) / / "I am a text"
    

Add a node to the page

  • appendChild: appends a node to the end of an element node

  • Syntax: parent node AppendChild (child node to insert)

    // Create a div element node var odiv = document createElement('div')var oText = document. CreateTextNode ('I am a text ') / / append a text node odiv appendChild(oText)console. Log (odiv) / / < div > I am a text < / div >
    
  • insertBefore: inserts a node before a node

  • Syntax: parent node InsertBefore (the node to be inserted, in front of which node)

    <body>  <div>    <p>I am a p label</p>  </div>    <script>  	var oDiv = document.querySelector('div')    var oP = oDiv.querySelector('p')        // Create an element node var OSPAN = document CreateElement ('span ') / / add this element node to odiv before P under Div insertBefore(oSpan, oP)        console. log(oDiv)    /*     	< div>     		< span></span>     		< p> I am a p tag</p> 	</ div>    */  </script></body>
    

Delete a node in the page

  • removeChild: removes a node under a node

  • Syntax: parent node Removechild (byte point to be removed)

    <body>  <div>    <p>I am a p label</p>  </div>    <script>  	var oDiv = document.querySelector('div')    var oP = oDiv.querySelector('p')        // Remove the p tag odiv. Under Div removeChild(oP)        console. log(oDiv) // <div></div>  </script></body>
    

Modify a node in the page

  • replaceChild: replace a node in the page

  • Syntax: parent node Replacechild (new node, old node)

    <body>  <div>    <p>I am a p label</p>  </div>    <script>  	var oDiv = document.querySelector('div')    var oP = oDiv.querySelector('p')        // Create a span node var OSPAN = document CreateElement ('span ') / / add some text OSPAN to the span element InnerHTML = 'I am a newly created span tag' 	//  Replace the p label odiv under the original div with the created span label replaceChild(oSpan, oP)        console. log(oDiv)    /*     	< div>     		< Span > I am a newly created span tag</span> 	</ div>    */  </script></body>
    

Gets the non line style of the element

  • When we operate DOM, a very important point is to operate the css style of elements

  • When operating css style, we can't avoid getting the style of elements

  • As we said before, we can use elements style.xxx to get

  • However, this method can only get the element inter line style, that is, the style written in the line

    <style>  div {    width: 100px;  }</style><body>  <div style="height: 100px;">    <p>I am a p label</p>  </div>  <script>    var oDiv = document.querySelector('div')		console.log(oDiv.style.height) // 100px    console.log(oDIv.style.width) // ''  </script></body>
    
  • We can't get the style of this element whether it's external chained or embedded

  • Here we will use the method to get getComputedStyle and currentStyle

  • The functions of these two methods are the same, except one in non IE browser and one in IE browser

getComputedStyle (not used by IE)

  • Syntax: window Getcomputedstyle (element, null) Properties to get

    <style>  div {    width: 100px;  }</style><body>  <div style="height: 100px;">    <p>I am a p label</p>  </div>  <script>    var oDiv = document.querySelector('div')		console.log(window.getComputedStyle(oDiv).width) // 100px    console.log(window.getComputedStyle(oDiv).height) // 100px  </script></body>
    
    • This method can obtain both inter line style and non inter line style

currentStyle (used by IE)

  • Syntax: elements currentStyle. Properties to get

    <style>  div {    width: 100px;  }</style><body>  <div style="height: 100px;">    <p>I am a p label</p>  </div>  <script>    var oDiv = document.querySelector('div')		console.log(oDiv.currentStyle.width) // 100px    console.log(oDiv.currentStyle.height) // 100px  </script></body>
    

Gets the offset of the element

  • Is the distance of the element on the page relative to the left and top of the reference parent

offsetParent

  • Gets the offset reference parent of the element
  • In fact, suppose you want to give an element absolute positioning
  • According to whom is it located
  • Who is the offset reference parent of this element

offsetLeft and offsetTop

  • Get the offset on the left side of the element and the offset on the upper side
  • offsetLeft: the left offset of the element relative to the reference parent
  • offsetTop: the upper offset of the element relative to the reference parent

Get element size

  • Is to get the "floor area" of the element

offsetWith and offsetHeight

  • offsetWidth: get the width of element content + padding + border
  • offsetHeight: get the height of element content + padding + border

clientWidth and clientHeight

  • clientWidth: gets the width of element content + padding

  • clientHeight: get the height of element content + padding

be careful

  • The obtained dimension is a number without units
  • When the element does not occupy a position in the page, it gets 0
    • display: none; Element does not occupy a space on the page
    • visibility: hidden; Element occupying space on page

Get browser window size

  • We learned innerWidth and innerHeight before

  • What they get is the size of the window containing the scroll bar

  • Next, let's learn two ways to obtain the size without scroll bars

  • document.documentElement.clientWidth: the width of the visual window

  • document.documentElement.clientHeight: the height of the visual window

EVENT

  • Before, we had a brief understanding of some events, such as onclick / onload / onscroll /
  • Starting today, we will learn some events in detail

What is an event

  • What does an event consist of

    • Whose event is triggered: event source
    • What event is triggered: event type
    • What to do after triggering: event handler
    var oDiv = document.querySelector('div')
    
    oDiv.onclick = function () {}
    // Who will trigger the event = > oDiv = > the event source of this event is oDiv
    // What event is triggered = > onclick = > this event type is click
    // What to do after triggering = > function() {} = > handler of this event
    
    • If we want to do anything after clicking div, we will write what we want to do in the event handler function
    var oDiv = document.querySelector('div')
    
    oDiv.onclick = function () {
      console.log('You clicked div')
    }
    
    • When we click div, the code inside the event handler will be executed
    • The event handler is executed once for each click

Event object

  • What is an event object?

  • When you trigger an event, some description information of the event

  • For example:

    • When you trigger a click event, where do you click and what are the coordinates
    • When you trigger a keyboard event, which button do you press
    • ...
  • Each event will have a corresponding object to describe this information. We call this object event object

  • The browser gave us a black box called window Event is all descriptions of event information

    • For example, click event
    • If you click on position 0 and 0, the event object you get will have the attribute of this point
    • If you click on position 10, 10, the event object you get will have the attribute of this point
    • ...
    oDiv.onclick = function () {
      console.log(window.event.X Axis coordinate point information)
      console.log(window.event.Y Axis coordinate point information)
    }
    
  • This thing is very easy to use, but generally speaking, easy-to-use things will have compatibility problems

  • This is easy to use in the low version of IE, but it is not easy to use in the high version of IE and Chrome

  • We have to get the event object in another way

  • In the row parameter position of each event handler function, the default first is the event object

    oDiv.onclick = function (e) {
      // e is the window with IE Event is the same thing
      console.log(e.X Axis coordinate point information)
      console.log(e.Y Axis coordinate point information)
    }
    
  • To sum up, we will use compatible writing when we want to obtain event objects in each event in the future

    oDiv.onclick = function (e) {
      e = e || window.event
      console.log(e.X Axis coordinate point information)
      console.log(e.Y Axis coordinate point information)
    }
    

Click the cursor coordinate point of the event to obtain

  • As I said just now, you can obtain coordinate points. Next, let's learn how to obtain coordinate points
  • The coordinate points of each click event are not a pair, because there should be a relative coordinate system
  • For example:
    • Relative event source (the element you clicked)
    • Relative page
    • Relative browser window
    • ...
  • Because they are different, the properties in the event object we get are also different

Relative to the element you click

  • offsetX and offsetY

  • Is calculated relative to the inside of the border of the element you click

    <style>
      * {
        margin: 0;
        padding: 0;
      }
    
      div {
        width: 300px;
        height: 300px;
        padding: 20px;
        border: 10px solid #333;
        margin: 20px 0 0 30px;
      }
    </style>
    <body>
      <div></div>
    
      <script>
        var oDiv = document.querySelector('div')
    
        // Register click events
        oDiv.onclick = function (e) {
          // Event object compatible writing
          e = e || window.event
    
          console.log(e.offsetX)
          console.log(e.offsetY)
        }
      </script>
    </body>
    

    [the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-e73V40zl-1626013036403)(C:/Users / simple point / Desktop / profile / assets/offset.jpg)]

The coordinate point you click relative to the browser window

  • clientX and clientY

  • It is calculated relative to the browser window. No matter what the page scrolls to, the coordinates are calculated according to the window

    <style>
      * {
        margin: 0;
        padding: 0;
      }
    
      body {
        width: 2000px;
        height: 2000px;
      }
    
      div {
        width: 300px;
        height: 300px;
        padding: 20px;
        border: 10px solid #333;
        margin: 20px 0 0 30px;
      }
    </style>
    <body>
      <div></div>
    
      <script>
        var oDiv = document.querySelector('div')
    
        // Register click events
        oDiv.onclick = function (e) {
          // Event object compatible writing
          e = e || window.event
    
          console.log(e.clientX)
          console.log(e.clientY)
        }
      </script>
    </body>
    

    [the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-sGA2qdQL-1626013036403)(C:/Us9ers / simple point / Desktop / personal data / assets/client.jpg)]

The coordinate point you click relative to the page

  • pageX and pageY

  • It is the coordinate point relative to the whole page. Whether it is scrolled or not, it is the coordinate point relative to the page

    <style>
      * {
        margin: 0;
        padding: 0;
      }
    
      body {
        width: 2000px;
        height: 2000px;
      }
    
      div {
        width: 300px;
        height: 300px;
        padding: 20px;
        border: 10px solid #333;
        margin: 20px 0 0 30px;
      }
    </style>
    <body>
      <div></div>
    
      <script>
        var oDiv = document.querySelector('div')
    
        // Register click events
        oDiv.onclick = function (e) {
          // Event object compatible writing
          e = e || window.event
    
          console.log(e.pageX)
          console.log(e.pageY)
        }
      </script>
    </body>
    

    [the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-mp6HvqQ6-1626013036404)(C:/Users / simple point / Desktop / profile / assets/page.jpg)]

  • According to the upper left corner of the page

    • Margin left is 30
    • The left border is 10
    • The left and right padding are 20 respectively
    • The content area is 300
    • pageX : 300 + 20 + 20 + 10 + 30 = 380
    • Margin top is 20
    • The top border is 10
    • The upper and lower padding are 20 each
    • The content area is 300
    • pageY : 300 + 20 + 20 + 10 + 20 = 270

Click key information (understand)

  • Our mouse usually has two buttons, a left button and a right button
  • We also have this information in the event object. Make sure you click the left or right button
  • We use event objects button to get information
  • 0 is the left mouse button and 2 is the right mouse button

Common events (understand)

  • Some events we often use when writing pages
  • It can be roughly divided into several categories: browser event / mouse event / keyboard event / form event / touch event
  • You don't have to remember everything, but you probably need to know

Browser events

  • load: all resources on the page are loaded
  • scroll: triggered when the browser scrolls
  • ...

Mouse event

  • Click: click event
  • dblclick: double click the event
  • Context menu: right click the event
  • mousedown: left mouse button press event
  • mouseup: left mouse button lift event
  • mousemove: mouse movement
  • mouseover: mouse in event
  • mouseout: mouse out event
  • mouseenter: mouse in event
  • mouseleave: mouse move out event
  • ...

Keyboard events

  • keyup: keyboard lift event
  • keydown: keyboard press event
  • keypress: keyboard press and lift event
  • ...

Form Events

  • Change: form content change event
  • Input: form content input event
  • submit: form submission event
  • ...

Touch event

  • touchstart: touch start event
  • touchend: touch end event
  • touchmove: touch move event
  • ...

Keyboard events

  • I just learned about mouse events. Now let's talk about keyboard events

  • The most important thing we do in keyboard events is to do two things

    • Determine which button is clicked
    • Is there a combination of keys, shift + a / ctrl + b /
  • Let's first clarify the problem, that is, can all elements be bound to keyboard events

    • We say that the key thing about the event is who triggered the event
    • If a div element is on the page, how can I trigger a keyboard event on the div
    • Therefore, we usually only bind keyboard events to the elements (form elements) and document s that can be selected on the page
    document.onkeyup = function () { // code.. } oInput.onkeyup = function () { // code.. }
    

OK key

  • Each key on our keyboard has its own independent code

  • We rely on this code to determine which button we press

  • We use event objects keyCode or event object which to get

  • Why two? It's because of Firefox 2 0 does not support keycode, so which should be used

    document.keyup = function (e) {  // Compatible writing of event object e = e | window Event / / obtain the compatible writing method of keyboard code var keycode = e.keycode | e.Which console log(keyCode)}
    

Common keyboard codes (understand)

  • 8: delete key
  • 9: tab
  • 13: Enter (ebter)
  • 16: Up shift key
  • 17: ctrl key
  • 18: alt key
  • 27: cancel key (esc)
  • 32: space
  • ...

Combination key

  • The most important combination of cases is the alt / shift / ctrl buttons

  • When I click a key, judge whether the three keys are pressed. If there is a combination, there is no combination

  • The event object also provides us with three properties

    • altKey: press the alt key to get true, otherwise get false
    • shiftKey: press the shift key to get true, otherwise get false
    • ctrl key: press the ctrl key to get true, otherwise get false
  • We can use these three attributes to determine whether it is pressed

    document.onkeyup = function (e) {  e = e || window.event  keyCode = e.keyCode || e.which    if (e.altKey && keyCode === 65) {    console.log('You pressed it at the same time alt and a')  }}
    

Event binding method

  • We now use onxxx to register events

  • However, this method is not very good. Only one event can be registered for one element

  • Once the second event is written, the first is overwritten

    oDiv.onclick = function () {  console.log('I was the first event')}oDiv.onclick = function () {  console.log('I am the second event')}
    
    • When you click, only the second one will be executed, and the first one will be gone
  • We also have an event listening method to bind events to elements

  • Add using addEventListener

    • This method is incompatible. attachEvent should be used in IE

event listeners

  • addEventListener: not used under IE 7 8

  • Syntax: elements addEventListener('event type ', event handler, bubble or capture)

    oDiv.addEventListener('click', function () {  console.log('I was the first event')}, false)oDiv.addEventListener('click', function () {  console.log('I am the second event')}, false)
    
    • When you click div, both functions will execute in the order you registered
    • Print me as the first event and then print me as the second event
    • Note: don't write on when you click an event type. Clicking an event is click, not onclick
  • attachEvent: used under IE 7 8

  • Syntax: elements attachEvent('event type ', event handler function)

    oDiv.attachEvent('onclick', function () {  console.log('I was the first event')})oDiv.attachEvent('onclick', function () {  console.log('I am the second event')})
    
    • When you click div, both functions will be executed and will be flashed in the order you registered
    • Print me as the second event first, and then print me as the first event
    • Note: when the event type is selected, write on, and click onclick

The difference between the two ways

  • Writing of event type parameters when registering events
    • addEventListener: don't write on
    • attachEvent: to write on
  • Number of parameters
    • addEventListener: three common parameters
    • attachEvent: two parameters
  • Execution sequence
    • addEventListener: register in sequence and execute in sequence
    • attachEvent: sequential registration, flashback execution
  • Applicable browser
    • addEventListener: Browser other than IE 7 8
    • attachEvent: IE 7 8 browser

What is the execution mechanism of events?

  • Think about a question?

  • When a large box is nested with a small box, and both boxes have click events

  • Do you want to execute the click event on the small box inside and the large box outside

    [the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-cV0W9Wpi-1626013036405)(C:/Users / simple point / Desktop / profile / assets/event propagation. jpg)]

Propagation of events

  • Just like the picture above, when we click on the red box, we also click on the pink box
  • This is an established fact, so the click events of both boxes will be triggered
  • This is called event propagation
    • When an element triggers an event, its parent element will also trigger the same event, and the parent element of the parent element will also trigger the same event
    • Just like the picture above
    • When clicking on the red box, the click event of the red box will be triggered
    • Clicking on the pink box will also trigger the click event of the pink box
    • Clicking on the body will also trigger the click event of the body
    • Clicking on html will also trigger the click event of html
    • Clicking on a document will also trigger a document click event
    • Clicking on the window will also trigger the window click event
    • In other words, the triggering event of any element on the page will lead to the triggering of the same event in the window layer by layer. The premise is that the same event must be registered for the elements at all levels, otherwise it will not be triggered
  • In the process of event propagation, there are some points to pay attention to:
    1. Only similar events will be propagated
    2. The event that will only start from clicking on the element and go up layer by layer according to the structure of html will be triggered
    3. Whether the internal element has this event or not, as long as the upper element has this event, the event of the upper element will be triggered
  • Now that we have understood the spread of events, let's think about another problem
    • The event will indeed start from itself, and all the same events to the window will be triggered
    • Because we point at ourselves, and we do point at every element up to the window layer by layer
    • But is it on yourself or on window first
    • Start with yourself, that is, first execute your own event handling function, step up layer by layer, and finally execute the event handling function of window
    • On the contrary, it first executes the event processing function of window, then executes the event processing function of itself layer by layer

Bubble, capture, target

  • As we talked just now, each event is possible from itself to the window, and multiple events of the same type may be executed
  • Then there are some statements about the order of execution

target

  • What element did you click on, and what is the goal of this event

Bubbling

  • It starts from the event handler function of the event target, and then outward in turn until the event handler function of window is triggered
  • That is, execute the event handler from bottom to top

capture

  • It starts from the event handler function of window and then inward, as long as the event handler function of the event target executes
  • That is, the event handler is executed from top to bottom

Difference between bubbling and trapping

  • That is, in the event propagation, the execution order of multiple event handling functions of the same type is different

Event delegation

  • Is to entrust what I want to do to others
  • Because of our bubbling mechanism, when clicking a child element, the same event of the parent element will be triggered synchronously
  • So we can delegate the events of the child element to the parent element

Event trigger

  • When clicking on a child element, regardless of whether the child element has a click event or not, as long as the parent element has a click event, the click event of the parent element can be triggered

    <body>
      <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
      </ul>
      <script>
      	var oUl = docuemnt.querySelector('ul')
        
        oUl.addEventListener('click', function (e) {
          console.log('I am ul Click event, I was triggered')
        })
      </script>
    </body>
    
    • Like the above code, it will trigger when you click ul
    • But when you click li, it will also trigger

target

  • The target attribute is the attribute in the event object, indicating the target you clicked

  • When you trigger a click event, the target is the element on which you click

  • This target is also incompatible. Srclelement should be used under IE

    <body>
      <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
      </ul>
      <script>
      	var oUl = docuemnt.querySelector('ul')
        
        oUl.addEventListener('click', function (e) {
          e = e || window.event
          var target = e.target || e.srcElement
          console.log(target)
        })
      </script>
    </body>
    
    • In the above code, when you click ul, the target is ul
    • When you click on li, the target is li

entrust

  • At this time, when we click li, the point event of ul can also be triggered

  • And in the event, we can also get whether you click on ul or li

  • At this time, we can entrust the li event to ul

    <body>
      <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
      </ul>
      <script>
      	var oUl = docuemnt.querySelector('ul')
        
        oUl.addEventListener('click', function (e) {
          e = e || window.event
          var target = e.target || e.srcElement
         
          // Judge whether you clicked li
          if (target.nodeName.toUpperCase === 'LI') {
          	// Make sure you click li
            // Because when you click on UL, nodeName should be 'UL'
            // Do what you should do when you click li
            console.log('I am li,I was clicked')
          }
        })
      </script>
    </body>
    
    • With the above code, we can delegate what li wants to do to ul

summary

  • Why use event delegates
    • There is no li on my page
    • I added some li through the code
    • The added li has no click event
    • Every time I dynamically operate li, I will bind a click event to li again
    • More trouble
    • At this time, just entrust it to ul
    • Because the newly added li is also a child element of ul, the click event of ul can also be triggered when clicking
  • Writing of event delegation
    • The event of an element can only be delegated to the same event of the structure parent or re structure parent
    • li's click event cannot be delegated to ul's mouse move in event
    • The click event of li can only be delegated to ul or on the click event of higher parent

Default behavior

  • The default behavior is that it exists without us registering
    • For example, when we click the right mouse button, a menu will pop up automatically
    • For example, when we click the a tag, we don't need to register the click event, and he will jump to the page himself
    • ...
  • These things that can be implemented without registration are called default events

Block default behavior

  • Sometimes we don't want the browser to execute default events

    • For example, I bind a click event to a tag. When I click on you, I hope you can tell me your address
    • Instead of jumping directly to the link
    • Then we need to block the original default event of a tag and prevent it from executing the default event
  • We have two ways to block default events

    • e.preventDefault(): not used by IE
    • e.returnValue = false: used by IE
  • When we block the default event, we should also write a compatible writing method

    <a href="https://www.baidu. Com "> Click me to try</a>
    <script>
    	var oA = document.querySelector('a')
      
      a.addEventListener('click', function (e) {
        e = e || window.event
        
        console.log(this.href)
        
        e.preventDefault ? e.preventDefault() : e.returnValue = false
      })
    </script>
    
    • After writing this way, when you click the a tab, you won't jump to the link
    • Instead, the value of the href attribute of the a tag will be printed out on the console

regular

  • Regular expression, also known as "regular expression"

  • We write the "rule" ourselves, which is specially used to detect whether the string meets the requirements of the "rule"

  • We use some special characters or symbols to define a "rule formula", and then use our defined "rule formula" to detect whether the string is qualified

    var reg = /\d+/
    var str1 = '123'
    var str2 = 'abc'
    console.log(reg.test(str1)) // true
    console.log(reg.test(str2)) // false
    
    • The above variable reg is the customized rule
    • When detecting the str1 string, the rule is met
    • When detecting the str2 string, it does not comply with the rules

Create a regular expression

  • If you want to formulate "rules", you must formulate them in the way required by others
  • Things that write letters and symbols in the middle of / / are called regular expressions, such as / abcdefg/
  • There are two ways to create regular expressions: literal and constructor

Literal creation

// Here is the literal to create a regular expression
var reg = /abcdefg/
  • This regular expression can detect strings

Constructor creation

// Here is the constructor to create a regular expression
var reg = new RegExp('abcdefg')
console.log(reg) //  /abcdefg/
  • The result is the same for those created by constructor and literal

Symbols in regular expressions

  • After knowing how to create a regular expression, let's talk about some symbols involved in the regular expression in detail

Metacharacter

  • .: matches any character that is not newline

  • \: Translate symbols, convert meaningful symbols into meaningless characters, and convert meaningless characters into meaningful symbols

  • \s: Match white space characters (spaces / tabs /...)

  • \S: Match non white space characters

  • \d: Match number

  • \D: Match non numeric

  • \w: Match alphanumeric underscores

  • \W: Match non numeric letter underscores

  • With metacharacters, we can simply make some rules

    var reg = /\s/
    var str = 'a b'
    var str2 = 'ab'
    console.log(reg.test(str)) // true
    console.log(reg.test(str2)) // false
    
    var reg = /\d/
    var str = 'abc1'
    var str2 = 'abc'
    console.log(reg.test(str)) // true
    console.log(reg.test(str2)) // false
    
    var reg = /\w/
    var str = 'a1'
    var str2 = '#@$'
    console.log(reg.test(str)) // true
    console.log(reg.test(str2)) // false
    

qualifier

  • *: the previous content is repeated at least 0 times, that is, it can appear 0 ~ positive infinite times

  • +: the previous content is repeated at least once, that is, it can occur 1 ~ positive infinite times

  • ? : The previous content is repeated 0 or 1 times, that is, it can appear 0 ~ 1 times

  • {n} : the previous content is repeated N times, that is, it must appear n times

  • {n,}: the previous content appears at least N times, that is, N ~ positive infinite times

  • {n,m}: the previous content appears at least N times and at most m times, that is, N ~ m times

  • Qualifiers are used with metacharacters

    // The following regular means that the verification number can appear 0 ~ positive infinity
    var reg = /\d*/
    var str = 'abc'
    var str2 = 'abc1'
    var str3 = 'abc123'
    console.log(reg.test(str)) // true
    console.log(reg.test(str2)) // true
    console.log(reg.test(str3)) // true
    
    // The following regular means that the verification number can appear 1 ~ positive infinity
    var reg = /\d+/
    var str = 'abc'
    var str2 = 'abc1'
    var str3 = 'abc123'
    console.log(reg.test(str)) // false
    console.log(reg.test(str2)) // true
    console.log(reg.test(str3)) // true
    
    // The following regular means that the verification number can appear 0 ~ 1 times. Var reg = / \ D/ var str = 'abc'var str2 = 'abc1'console. log(reg.test(str)) // trueconsole. log(reg.test(str2)) // true
    
    // The following regular means that the verification number must appear 3 times. Var reg = / \ D {3} / var STR = 'abc'var STR2 =' abc1'var str3 = 'abc123'console log(reg.test(str)) // falseconsole. log(reg.test(str2)) // falseconsole. log(reg.test(str3)) // true
    
    // The following regular indicates that the verification number appears 3 ~ positive infinity times, VAR reg = / \ D {3,} / var STR = 'abc'var STR2 =' abc1'var str3 = 'abc123'var str4 =' abcd1234567'console log(reg.test(str)) // falseconsole. log(reg.test(str2)) // falseconsole. log(reg.test(str3)) // trueconsole. log(reg.test(str4)) // true
    
    // The following regular means that the verification number can only appear 3 ~ 5 times. Var reg = / \ D {3,5} / var STR = 'abc'var STR2 =' abc1'var str3 = 'abc123'var str4 =' abc12345'console log(reg.test(str)) // falseconsole. log(reg.test(str2)) // falseconsole. log(reg.test(str3)) // trueconsole. log(reg.test(str4)) // true
    

Boundary character

  • ^: indicates the beginning

  • $: indicates the end

  • A delimiter defines the beginning and end of a string

    // The following indicates that there can only be numbers from the beginning to the end, and they occur 3 ~ 5 times. Var reg = / ^ \ d{3,5} $/ var STR = 'abc'var STR2 =' abc123'var str3 = '1'var str4 =' 1234567'var str5 = '123'var str6 =' 12345'console log(reg.test(str)) // falseconsole. log(reg.test(str2)) // falseconsole. log(reg.test(str3)) // falseconsole. log(reg.test(str4)) // falseconsole. log(reg.test(str5)) // trueconsole. log(reg.test(str6)) // true
    

Special symbols

  • (): defines a set of elements

  • []: character set, indicating that any character written in []

  • [^]: inverse character set, indicating that any character other than that written in [^] is OK

  • -: range, e.g. a-z means from letter a to letter z

  • |: or, or a|b in the regular form means that the letter A or B can be used

  • Now we can combine several symbols together

    // The following is a simple mailbox verification / / non_$ At the beginning, any character appears at least 6 times, an @ symbol, any one of (163|126|qq|sina), any one of (com|cn|net) var reg = / ^ [^ $] {5,}@(163|126|qq|sina)\. (com|cn|net)$/
    

identifier

  • i: Indicates that case is ignored
    • This i is written at the end of regular
    • /\w/i
    • It is not case sensitive in regular matching
  • g: Represents a global match
    • This g is written at the end of the regular
    • /\w/g
    • Is the global match alphanumeric underscore

Regular expression method

  • Regular provides some methods for us to use
  • Used to detect and capture the contents of a string

test

  • test is used to check whether the string meets our regular criteria

  • Syntax: regular Test (string)

  • Return value: boolean

    console.log(/\d+/.test('123')) // trueconsole.log(/\d+/.test('abc')) // false
    

exec

  • exec is to capture the qualified content in the string

  • Syntax: regular Exec (string)

  • Return value: returns the first item in the string that meets the regular requirements and some other information in the form of an array

    var reg = /\d{3}/var str = 'hello123world456 Hello 789'var res = reg.exec(str)console.log(res)/*	["123", index: 5, input: "hello123world456 Hello 789 ", groups: undefined] 0:" 123 "groups: undefined index: 5 input:" hello123world456hello 789 "length: 1 	__ proto__: Array(0)*/
    
    • Item 0 of the array is the content of the matched string
    • The index property indicates the number of matches from the index of the string to the string

String method

  • There are some methods in strings that can also be used with regular strings

search

  • search is to find whether there is content in the string that meets the regular condition

  • Syntax: string Search (regular)

  • Return value: If yes, the start index is returned, but - 1 is not returned

    var reg = /\d{3}/var str = 'hello123'var str2 = 'hello'console.log(str.search(reg)) // 5console.log(str2.search(reg)) // -1
    

match

  • match finds the content in the string that meets the regular conditions and returns

  • Syntax: string Match (regular)

  • Return value:

    • When there is no identifier g, it is the same as the exec method
    • When there is the identifier g, it returns an array containing each matched item
    var reg = /\d{3}/var str = 'hello123world456'var str2 = 'hello'console.log(str.match(reg)) // ["123", index: 5, input: "hello123wor456", groups: undefined]console.log(str2.match(reg)) // null
    
    var reg = /\d{3}/gvar str = 'hello123world456'var str2 = 'hello'console.log(str.match(reg)) // ["123", "456"]console.log(str2.match(reg)) // null
    

replace

  • Replace is to replace the string that meets the regular condition in the string

  • Syntax: string Replace (regular, string to replace)

  • Return value: replaced string

    var reg = /\d{3}/var str = 'hello123world456'var str2 = 'hello'console.log(str.replace(reg)) // hello666world456console.log(str2.replace(reg)) // hello
    
    var reg = /\d{3}/gvar str = 'hello123world456'var str2 = 'hello'console.log(str.replace(reg)) // hello666world666console.log(str2.replace(reg)) // hello
    

ES6

  • What we call ES5 and ES6 is actually a version in the development of js syntax
  • For example, we use wechat
    • The earliest version had no payment function
    • With the passage of time, a version appeared later, which has the payment function
  • ECMAScript is the syntax of js
    • Previous versions did not have some features
    • Some functions have been added in the ES5 version
    • Some functions have been added in ES6
  • Because browsers are produced by browser manufacturers
    • After ECMAScript releases new functions, browser manufacturers need to make their browsers support these functions
    • This process takes time
    • So up to now, most browsers can be more fully supported
    • But some browsers still can't support it all
    • This raises compatibility issues
    • So when we write code, we should consider which methods are ES5 or ES6, and see if browsers support them

New content in ES6

  • The previous content is ES5
  • Next, let's talk about ES6

let and const keywords

  • We used to use the var keyword to declare variables

  • In ES6, there are two more keywords let and const, which are also used to declare variables

  • It's just different from var

    1. let and const do not allow duplicate declaration of variables

      // It's OK to declare variables repeatedly when using var, but the front will be overwritten later
      var num = 100
      var num = 200
      
      // An error will be reported when using let to declare variables repeatedly
      let num = 100
      let num = 200 // There will be a mistake here
      
      // When using const to declare variables repeatedly, an error will be reported
      const num = 100
      const num = 200 // There will be a mistake here
      
    2. The variables declared by let and const will not be resolved during pre resolution (that is, there is no variable promotion)

      // Because of pre parsing (variable promotion), there is this variable in front, but there is no assignment
      console.log(num) // undefined
      var num = 100
      
      // Because let does not perform pre parsing (variable promotion), it directly reports an error
      console.log(num) // undefined
      let num = 100
      
      // Because const does not perform pre parsing (variable promotion), it directly reports an error
      console.log(num) // undefined
      const num = 100
      
    3. The variables declared by let and const will be limited by all code blocks

      // Only functions can limit the scope of variables declared by var, and others cannot
      if (true) {
        var num = 100
      }
      console.log(num) // 100
      
      // For variables declared by let, except for functions, all code blocks can limit their scope (if/while/for /...)
      if (true) {
        let num = 100
        console.log(num) // 100
      }
      console.log(num) // report errors
      
      // For variables declared by const, except functions, all code blocks can limit their scope (if/while/for /...) if (true) {  const num = 100  console.log(num) // 100}console.log(num) / / an error is reported
      
  • The difference between let and const

    1. The value of the variable declared by let can be changed, and the value of the variable declared by const cannot be changed

      let num = 100num = 200console.log(num) // 200
      
      const num = 100num = 200 // An error will be reported here, because the variable value declared by const cannot be changed (we also call it a constant)
      
    2. let can be declared without assignment, and const must be declared with assignment

      let numnum = 100console.log(num) // 100
      
      const num // An error will be reported here, because the const declaration must be assigned a value
      

Arrow function

  • Arrow function is the syntax of a short function in ES6

  • Important: arrow functions can only be short for function expressions, not declarative functions

    function fn() {} // Cannot be abbreviated const fun = function() {} / / can be abbreviated const obj = {FN: function() {} / / can be abbreviated}
    
  • Syntax: (line parameter of function) = > {code to be executed in function body}

    const fn = function (a, b) {  console.log(a)  console.log(b)}// You can use the arrow function to write const fun = (a, b) = > {console.log (a) console.log (b)}
    
    const obj = {  fn: function (a, b) {    console.log(a)    console.log(b)  }}// You can use the arrow function to write const obj2 = {FN: (a, b) = > {console.log (a) console.log (b)}}
    

Particularity of arrow function

  • There is no this inside the arrow function. This of the arrow function is this of the context

    // Count up at the position defined by the arrow function. This line can print this / / because this here is window / / so this inside the arrow function is windowconst obj = {FN: function() {console. Log (this)}, / / this position is the previous line of the arrow function, However, you cannot print this fun: () = > {/ / this in the arrow function is the previous line of the arrow function, and the position where you can print this console.log (this)}} obj fn()obj. fun()
    
    • Judging from our previous this point, both should point to obj
    • However, because fun is an arrow function, this does not point to obj, but to the outer layer of fun, that is, window
  • There is no argument parameter set inside the arrow function

    const obj = {  fn: function () {    console.log(arguments)  },  fun: () => {    console.log(arguments)  }}obj.fn(1, 2, 3) // Will print a pseudo array [1, 2, 3] obj Fun (1, 2, 3) / / an error will be reported directly
    
  • You can not write () when there is only one line parameter of a function. You must write () in other cases

    const obj = {  fn: () => {    console.log('There are no parameters, you must write parentheses')  },  fn2: a => {    console.log('A line parameter, you can not write parentheses')  },  fn3: (a, b) => {    console.log('Parentheses must be written for two or more parameters')  }}
    
  • When the function body has only one line of code, you can not write {} and will automatically return

    const obj = {  fn: a => {    return a + 10  },  fun: a => a + 10}console.log(fn(10)) // 20console.log(fun(10)) // 20
    

The default value when a function passes parameters

  • When we define a function, sometimes we need a default value to appear

  • When I don't pass parameters, I use the default value. When I pass parameters, I use the passed parameters

    function fn(a) {  a = a || 10  console.log(a)}fn()   // When the parameter is not passed, the internal a of the function is 10fn(20) / / when the parameter 20 is passed, the internal a of the function is 20
    
    • In ES6, we can directly write the default value in the row parameter position of the function
    function fn(a = 10) {  console.log(a)}fn()   // When the parameter is not passed, the internal a of the function is 10fn(20) / / when the parameter 20 is passed, the internal a of the function is 20
    
    • The default value of the arrow function can also be used
    const fn = (a = 10) => {  console.log(a)}fn()   // When the parameter is not passed, the internal a of the function is 10fn(20) / / when the parameter 20 is passed, the internal a of the function is 20
    
    • Note: if you need to use the default value of the arrow function, you also need to write () for a parameter

Destructuring assignment

  • Deconstruction assignment is a syntax way to quickly extract members from objects or arrays

Deconstruction object

  • Quickly get members from objects

    // The method of ES5 obtains the member const obj = {Name: 'Jack', age: 18, gender: 'male'} let name = obj namelet age = obj. agelet gender = obj. gender
    
    // Deconstruct the assignment method to get members from the object const obj = {Name: 'Jack', age: 18, gender: 'male'} / / the previous {} indicates that I want to get members from obj. / / name, age, gender must be some members of obj. / / obj must be an object let {name, age, gender} = obj
    

Deconstruct array

  • Quickly get members from the array

    // ES5 obtains members from the array const arr = ['Jack ',' Rose ',' Tom '] let a = arr [0] let B = arr [1] let C = arr [2]
    
    // Obtain members from the array by deconstruction assignment. Const arr = ['Jack ',' Rose ',' Tom '] / / the preceding [] indicates that you want to obtain members from the array of arr. / / A, B, C correspond to the indexes 0, 1, 2 in the array respectively. / / arr must be an array let [a, b, c] = arr
    

be careful

  • {} is specifically used to deconstruct objects
  • [] is specially used to deconstruct arrays
  • Can not be mixed

Template string

  • In ES5, we use '' or '' when representing strings

  • In ES6, we have another thing that can represent strings, which is ` ` (back quotation marks)

    let str = `hello world`console.log(typeof str) // string
    
  • The difference between single quotation marks and double quotation marks

    1. Back quotation marks can be written on a new line

      // The single quotation mark or double quotation mark cannot be wrapped. If the quotation mark is wrapped, an error will be reported, let str = 'hello world' / / the following error will be reported, let str2 = 'hello world'
      
      let str = `	hello	world`console.log(str) // It can be used
      
    2. Backquotes can splice variables directly inside a string

      // When ES5 requires string splicing variables, let num = 100let STR ='Hello '+ num +'World' + numconsole Log (STR) / / hello100world100 / / it's hard to write directly in the string, so let STR2 = 'hellonumworldnum' console log(str2) // hellonumworldnum
      
      // Template string splicing variable let num = 100let STR = ` Hello ${num} world ${num} ` console log(str) // hello100world100
      
      • The ${} in ` ` is the position used to write variables

Expand operator

  • A new operator has been added to the number in ES6, It's called the expansion operator

  • The function is to expand the array

    let arr = [1, 2, 3, 4, 5]console.log(...arr) // 1 2 3 4 5
    
  • When merging arrays, you can use

    let arr = [1, 2, 3, 4]let arr2 = [...arr, 5]console.log(arr2)
    
  • You can also use merge objects

    let obj = {  name: 'Jack',  age: 18}let obj2 = {  ...obj,  gender: 'male'}console.log(obj2)
    
  • It can also be used when passing parameters to a function

    let arr = [1, 2, 3]function fn(a, b, c) {  console.log(a)  console.log(b)  console.log(c)}fn(...arr)// Equivalent to fn(1, 2, 3)
    

this keyword

  • Every function has a keyword this

  • We can use it directly

  • Important: this in the function is only related to the calling method of the function, not the definition method of the function

  • Who this points to in the function depends on the calling method of the function

    • Directly call the globally defined function, this = > window

      function fn() {  console.log(this)}fn()// this points to window
      
    • Object, this = > caller

      var obj = {  fn: function () {    console.log(this)  }}obj.fn()// this points to obj
      
    • Timer processing function, this = > window

      setTimeout(function () {  console.log(this)}, 0)// At this time, this in the timer processing function points to window
      
    • Event handler, this = > event source

      div.onclick = function () {  console.log(this)}// When you click div, this points to Div
      
    • Self calling function, this = > window

      (function () {  console.log(this)})()// this points to window
      

call and apply and bind

  • What we said just now is the basic calling method of the function. this point in it
  • We also have three this points that can ignore the function itself and point to other places
  • The three methods are call / apply / bind
  • Is a way to forcibly change the direction of this

call

  • The call method is used after the function call, and the this point of the function itself can be ignored

  • Syntax: function name Call (this point to be changed, parameter 1 to be passed to the function, parameter 2 to be passed to the function,...)

    var obj = { name: 'Jack' }function fn(a, b) {  console.log(this)  console.log(a)  console.log(b)}fn(1, 2)fn.call(obj, 1, 2)
    
    • fn(), this inside the function points to window
    • fn. When calling (obj, 1, 2), this in the function points to the object obj
    • When using the call method
      • The function is executed immediately
      • The first parameter is the this point inside the function you want to change
      • The second parameter starts with passing parameters to the function

apply

  • The apply method is used after the function call, and the this point of the function itself can be ignored

  • Syntax: function name Apply (this point to be changed, [parameter 1 to be passed to the function, parameter 2 to be passed to the function,...])

    var obj = { name: 'Jack' }function fn(a, b) {  console.log(this)  console.log(a)  console.log(b)}fn(1, 2)fn.call(obj, [1, 2])
    
    • fn(), this inside the function points to window
    • fn. When apply (obj, [1, 2]), this in the function points to the object obj
    • When using the apply method
      • The function is executed immediately
      • The first parameter is the this point inside the function you want to change
      • The second parameter is an array, and each item in the array is the parameter passed to the function in turn

bind

  • The bind method is used after the function call, and the this point of the function itself can be ignored

  • Unlike call / apply, it does not execute the function immediately, but returns a function that has changed the point of this

  • Syntax: var newFn = function name Bind (this point to be changed); Newfn (pass parameter)

    var obj = { name: 'Jack' }function fn(a, b) {  console.log(this)  console.log(a)  console.log(b)}fn(1, 2)var newFn = fn.bind(obj)newFn(1, 2)
    
    • When bind is called, fn this function will not be executed, but a new function will be returned
    • This new function is a fn function that changes the point of this
    • When fn(1, 2), this points to window
    • newFn(1, 2) executes the same function as fn, but the point of this is changed to obj

HTTP

  • http is the transport protocol (Hypertext Transport Protocol) when we interact with the front and back stations

Workflow of HTTP

  1. Link with server
  2. After establishing the link, send a request to the server (request)
  3. After receiving the request, the server processes it accordingly and gives a response (response)
  4. Disconnect from server

Link with server

  • How to establish a link with the server?

  • It is necessary to ensure that the client receives and sends normally, and the server receives and sends normally

  • This involves a thing called TCP/IP protocol

  • The main step in establishing a link is called a triple handshake

    1. The client sends a message to the server

      At this time:
      	The server knows that the client can send messages normally
      
  1. The server returns a message to the client

      At this time:
      	The server knows that the client can send messages normally
      	The server knows that the server can accept messages normally
      	The client knows that the client can send messages normally
      	The client knows that the client can accept messages normally
      	The client knows that the server can accept messages normally
      	The client knows that the server can send messages normally
    
  2. The client returns a message to the server

      At this time:
      	The server knows that the client can send messages normally
      	The server knows that the server can accept messages normally
      	The client knows that the client can send messages normally
      	The client knows that the client can accept messages normally
      	The client knows that the server can accept messages normally
      	The client knows that the server can send messages normally
      	The server knows that the server can send messages normally
      	The server knows that the client can accept messages normally
    
  • So far, the link is established according to the TCP/IP protocol

  • Both parties know that they can send and receive messages normally

  • You can go to the second step, communication

Send a request

  • After the link is established, it is the process of sending the request

  • Every request should include all our information

  • Each request will have a request message

  • The request message will contain all our request information (that is, what we want to say to the server is in it)

  • Our request message will contain several things

    1. Request line

      POST /user HTTP/1.1
      # POST request mode
      # /user request URL (excluding domain name)
      # HTTP/1.1 request protocol version
      
    2. Request header (request headers are all in the form of key value pairs)

      user-agent: Mozilla/5.0 # Generate requested browser information
      accept: application/json # Indicates the data type that the client wants to accept
      Content-Type: application/x-www-form-urlencoded # Entity data format sent by client
      Host: 127.0.0.1 # Requested host name (IP)
      
    3. Request blank line (leave a blank line between the request header and the request body)

      # It's an empty line
      
    4. Request body (data carried in this request)

      # The GET request has no request body data
      # Only POST requests have request body data
      
  • Next, let's look at a complete request message

    POST /user HTTP/1.1      # Request line
    Host: www.user.com
    Content-Type: application/x-www-form-urlencoded
    accept: application/json
    User-agent: Mozilla/5.0.     # The above is the first
    #((there must be a blank line here)  # Blank line splits header and request content 
    name=world   # Request body
    

Accept a response

  • After the client's request is sent to the server

  • The server performs corresponding processing

  • Will give us a response

  • Each response will have a response message

  • The response message will contain all our response information (that is, the reply given to us by the server after receiving the client's request)

  • Our response message will contain several information

    1. Status line

      HTTP/1.1 200 OK# HTTP/1.1 Server used HTTP Protocol version# 200 Response status code# OK is a simple explanation of the response status code
      
    2. Response header

      Date: Jan, 14 Aug 2019 12:42:30 GMT # Server time Server: Apache/2.4.23 (Win32) OpenSSL/1.0.2j PHP/5.4.45 # Server type Content-Type: text/html # Data type from server to client Content-Length: 11 # Data length from server to client
      
    3. Responder

      hello world# Response data from the server to the client
      

Break the link to the server

  • Our previous link establishment is a three-time handshake based on TCP/IP protocol
  • Our disconnection is based on four waves of TCP/IP protocol
    1. The client sends a message to the server that I want to disconnect
    2. After the server receives it, it sends a message to tell the client that I have entered the shutdown waiting state
    3. The server sends a message to the client again. This is my last message to you. When I receive the message again, it will be closed
    4. After receiving the message from the server, the client tells the server that I have shut down. This is the last message for you

Complete an HTTP request

  • At this point, an HTTP request is completed
  • The four steps that an HTTP request must include are
    1. Establish link
    2. Send request
    3. Accept response
    4. break link
  • In an HTTP request, the part of the request has a request message, and the part receiving the response has a response message
  • The request message contains
    1. Request line
    2. Request header
    3. Request blank line
    4. Request body
  • response message
    1. Status line
    2. Response header
    3. Responder

Common HTTP response status codes

  • The status line in the response message of an HTTP request will have a response status code
  • This status code is used to describe the status of this response
  • There are usually five status codes
    1. 100 ~ 199
    2. 200 ~ 299
    3. 300 ~ 399
    4. 400 ~ 499
    5. 500 ~ 599

100 ~ 199

  • Generally, we can't see it because it means that we request to continue

  • 100: continue the request. Some of the previous content servers have received it and are waiting for subsequent content

  • 101: the requester has prepared to switch the protocol, and the server page agrees

200 ~ 299

  • 2 indicates success. This request is successful, but different status codes have different meanings (semantics)
  • 200: the standard request is successful (generally, it means that the server provides a web page)
  • 201: successful creation (usually when registering, it means that the new user information has been added to the database)
  • 203: indicates that the server has successfully processed the request, but the returned information may come from another source
  • 204: the server has successfully processed the request, but no data is returned

300 ~ 399

  • 3 is also a success, but it generally means redirection
  • 301: permanent redirection
  • 302: temporary redirection
  • 304: cached data is used
  • 305: using agents

400 ~ 499

  • The beginning of 4 indicates that an error has occurred on the client
  • 400: the requested syntax is unknown to the server
  • 401: unauthorized (the website you want to log in to needs authorization to log in)
  • 403: the server rejected your request
  • 404: the server cannot find the URL you requested
  • 407: your agent is not authorized
  • 408: request timeout
  • 410: the data you requested has been permanently deleted by the server

500 ~ 599

  • 5 indicates an error on the server
  • 500: server internal error
  • 503: the server is currently unavailable (overload or maintenance)
  • 505: the requested protocol server does not support

Common HTTP request methods

  • Every HTTP request has a thing called request mode in the request line
  • Different request methods represent different meanings
    1. GET: generally used to obtain some information (GET list)
    2. POST: it is generally used to send some data to the server (login)
    3. PUT: it is generally used to send some data to the service when it is asked to add new data (Registration)
    4. DELETE: DELETE some data with fields
    5. HEAD: similar to a GET request, but generally there is no specific content of the response, which is used to obtain the message header
    6. CONNECT: the reserved method in HTTP/1.1 is generally used when the pipeline link is changed to a proxy
    7. PATCH: similar to PUT, it is generally used to update local data
    8. OPTIONS: allows the client to view the server performance
  • We often use GET and POST

GET request

  • Parameters are sent in the form of querystring, that is, they are directly spliced behind the request path
  • GET requests are actively cached by the browser
  • The length of GET requests is limited according to different browsers
    • IE: 2083 characters
    • FireFox: 65536 characters
    • Safari: 80000 characters
    • Opera: 190000 characters
    • Chrome: 8182 characters
    • APACHE(server): the theoretically accepted maximum length is 8192 characters (to be discussed)
  • There are restrictions on the type of parameters. Only ASCII format is accepted
  • GET requests are sent in clear text and are relatively insecure

POST request

  • Parameters are sent in the form of request body, that is, in the request body
  • POST requests are not actively cached by the browser unless manually set
  • POST requests are theoretically unlimited unless the server makes restrictions
  • There are no restrictions on parameter types. Theoretically, any data type can be passed, but it should correspond to the request header
  • The POST request is sent in ciphertext, which is relatively safe

COOKIE

  • A cookie is a location where data is stored as a string
  • Every HTTP request will carry a cookie to the server in the request header
  • Each HTTP response will carry a cookie to the client in the response header
  • In other words, cookie s are data that will automatically swim between the client and the server without our manual setting
  • We just need to set the contents of the cookie

Storage form of COOKIE

  • Cookies are stored in the form of strings, which appear in the form of key=value

  • Each key=value is a piece of data

  • Between multiple data; division

    // cookie form 'a=100; b=200; c=300;'
    

Features of COOKIE

  1. The storage size is limited, usually about 4 KB
  2. The number is limited, generally about 50
  3. It has timeliness, that is, it has expiration time, which is generally at the session level (that is, it expires when the browser is closed)
  4. There are domain name restrictions, that is, whoever sets it can read it

Mode of use

  • Read the contents of the cookie using document cookie

    const cookie = document.cookieconsole.log(cookie) // You can get the value of the current cookie
    
  • Set the contents of the cookie using document cookie

    // Set a cookiedocument with timeliness at the session level Cookie = 'a = 100' / / set a cookie document with expiration time cookie = 'b=200; Expires = Thu, 18 Dec 2043 12:00:00 GMT "; '/ / the above cookie data will expire after 12:00 on December 18, 2043, and will disappear automatically after expiration
    
  • Delete the contents of the cookie using document cookie

    // Because cookies cannot be deleted directly / / we can only set the expiration time of a cookie before the current time / / then the browser will automatically delete the cookie document cookie = 'b=200; expires=Thu, 18 Dec 2018 12:00:00 GMT";'
    

COOKIE operation package

  • Because there is no special method to add, delete, modify and query COOKIE in js
  • So we need to encapsulate a method ourselves

Set cookie s

/** * setCookie Used to set cookie * @param {STRING} key cookie name to be set * @ param {STRING} value cookie content to be set * @ param {NUMBER} expires expiration time */function setCookie (key, value, expires) {  const time = new Date()  time.setTime(time.getTime() - 1000 * 60 * 60 * 24 * 8 + expires) // Used to set the expiration time document cookie = `${key}=${value}; expires=${time};`}

Read cookie s

/**
 * getCookie Get a property in the cookie
 * @param {STRING} key cookie properties you want to query
 * @return {STRING} The value of the cookie attribute you want to query
 */
function getCookie(key) {
  const cookieArr = document.cookie.split(';')

  let value = ''

  cookieArr.forEach(item => {
    if (item.split('=')[0] === key) {
      value = item.split('=')[1]
    }
  })

  return value
}

Delete cookie

/**
 * delCookie Delete a property in the cookie
 * @param {STRING} name The name of a cookie property you want to delete
 */
function delCookie(name) {
  setCookie(name, 1, -1)
}
GET and POST Difference between requests ? (Read and recite the full text)
    GET
    1. Tend to get data from the server
    2. Splice directly behind the address(The request body is empty)
    3. Size limit is 2 KB about(because IE Pass up to 2 KB)
    4. Will be actively cached by the browser
    5. be relative to POST Not very safe(Plaintext transmission)
    6. Data format must be url Encoding format, If not, it will be automatically converted to url code

    POST
    1. Tends to pass data to the server
    2. Then pass it in the request body(Not after the address)
    3. In theory, there is no limit(But it can be limited by the server)
    4. Will not be actively cached by the browser, Manual setting required
    5. be relative to GET Relatively safe(Dark text transmission)
    6. Data format is what I call in theory, But it's the same as in the request header content-type agreement
    	=> In the request header content-type Represents the data format of the request body

    be careful:
    + When you need to deliver privacy information related to users, Must be used POST Mode sending
    + When I log in, Be sure to use it POST Send request by
cookie Characteristics of (Read and recite the full text)
    1. Store by domain name
    + Under which domain name do you store the content, Under which domain name
    + No other domain names can be used
    + It has nothing to do with the resource path address
    2. Limited storage size
    + 4KB about
    + 50 Left and right
    + Or your relationship
    3. Timeliness
    + The default is session level timeliness(Close the browser and it's gone)
    + It can be set manually, Seven days later, Two hours later
    4. Request auto carry
    + When you cookie When there is content in the space
    + As long as it is any request under the current domain name, Will be carried automatically cookie Put it in the request header
    => cookie How many are in it and how many are carried automatically
    + If cookie There is no content in the space, You won't carry it
    5. Front and rear end operation
    + The front end can pass through js operation cookie Add, delete, modify and query space
    + The backend can also be implemented in any backend language cookie Addition, deletion, modification and query of space

AJAX

  • ajax full name async javascript and XML
  • It is the ability of front and back interaction
  • That is, our client sends messages to the server and receives responses
  • Is a function of the default asynchronous execution mechanism

Advantages of AJAX

  1. Without the support of plug-ins, native js can be used
  2. Good user experience (data can be updated without refreshing the page)
  3. Reduce the burden of server and bandwidth
  4. Disadvantages: the support of the search engine is not enough, because the data is not on the page and the search engine cannot search

Use of AJAX

  • There is a built-in constructor in js to create ajax objects
  • After creating the ajax object, we use the method of the ajax object to send the request and receive the response

Create an ajax object

// IE9 and above
const xhr = new XMLHttpRequest()

// Below IE9
const xhr = new ActiveXObject('Mricosoft.XMLHTTP')
  • There is an ajax object above
  • We can use this xhr object to send ajax requests

Configure link information

const xhr = new XMLHttpRequest()

// The open method in the xhr object is used to configure the request information
// The first parameter is the request method of this request, get / post / put /
// The second parameter is the url of this request 
// The third parameter is whether the request is asynchronous. By default, true means asynchronous and false means synchronous
// xhr.open('request method ',' request address', asynchronous)
xhr.open('get', './data.php')
  • After the above code is executed, the basic configuration information of this request is written

Send request

const xhr = new XMLHttpRequest()
xhr.open('get', './data.php')

// Use the send method in the xhr object to send the request
xhr.send()
  • The above code is to send the configured ajax object to the server

A basic ajax request

  • One of the most basic ajax requests is the above three steps
  • But with the above three steps, we can indeed send the request to the server
  • If the server is normal, the response can also return to the client
  • But we can't get a response
  • If we want to get a response, we have two preconditions
    1. The HTTP request is successful, that is, the HTTP status code we mentioned earlier is 200 ~ 299
    2. The ajax object also has its own status code, which is used to represent each stage of the ajax request

ajax status code

  • ajax status code - XHR readyState
  • Is used to represent a state in the whole process of an ajax request
    • readyState === 0: indicates that the initialization is not completed, that is, the open method has not been executed
    • readyState === 1: indicates that the configuration information has been completed, that is, after the open is executed
    • readyState === 2: indicates that the send method has been executed
    • readyState === 3: indicates that the response content is being parsed
    • readyState === 4: indicates that the response content has been parsed and can be used on the client
  • At this time, we will find that in the whole process of an ajax request, we can normally use the data given to us by the server only when readyState === 4
  • Therefore, the matching http status code is 200 ~ 299
    • An ajax object has a member called XHR status
    • This member records the http status code of this request
  • When both conditions are met, the request is completed normally

readyStateChange

  • There is an event in the ajax object called the readyStateChange event

  • This event is specifically used to listen for changes in the readyState value of an ajax object

  • That is, the event will be triggered as long as the readyState value changes

  • So let's listen in this event to see if the readyState of ajax has reached 4

    const xhr = new XMLHttpRequest()
    xhr.open('get', './data.php')
    
    xhr.send()
    
    xhr.onreadyStateChange = function () {
      // This event is triggered every time the readyState changes
      // Here we judge whether the readyState value is 4
      // And is the status code of http 200 ~ 299
      if (xhr.readyState === 4 && /^2\d{2|$/.test(xhr.status)) {
        // This indicates that the verification is passed
        // We can get the content that the server responds to us
      }
    }
    

responseText

  • responseText member in ajax object

  • It is used to record the content of the response body given to us by the server

  • So we can use this member to get the content of the response body

    const xhr = new XMLHttpRequest()
    xhr.open('get', './data.php')
    
    xhr.send()
    
    xhr.onreadyStateChange = function () {
      if (xhr.readyState === 4 && /^2\d{2|$/.test(xhr.status)) {
        // We print XHR directly here ResponseText to view the content returned to us by the server
        console.log(xhr.responseText)
      }
    }
    

Parameters are carried when sending a request using ajax

  • We can also use ajax to send requests with parameters
  • Parameters are some information given to him when interacting with the background
  • However, there are differences between the two methods of carrying parameters get and post

Send a get request with parameters

  • The parameters of the get request can be spliced directly after the url

    const xhr = new XMLHttpRequest()
    // Add a?, directly after the address?, Then pass it in the form of key=value
    // The two data are separated by &
    xhr.open('get', './data.php?a=100&b=200')
    
    xhr.send()
    
    • In this way, the server can accept two parameters
    • One is a and the value is 100
    • One is b and the value is 200

Send a post request with parameters

  • The parameters of the post request are carried in the request body, so there is no need to splice after the url

    const xhr = new XMLHttpRequest()xhr.open('get', './data.php')// If you send a post request with an ajax object, you must first set the content type in the request header. / / tell the server what kind of data format I give you XHR Setrequestheader ('content type ',' application / x-www-form-urlencoded ') / / when the request body is sent directly, it can be written in () / / there is no question mark, it is in the form of' key = value & key = value 'XHR send('a=100&b=200')
    
    • The data format represented by application/x-www-form-urlencoded is key = value & key = value

Encapsulating AJAX

  • ajax is too cumbersome to use because you have to write a lot of code every time
  • So let's encapsulate an ajax method to make it easier for us to use

Determine how to use it

  • Because some contents can not be passed, we can use the default value, so we choose the method of object passing parameters

    // When using, call directly and pass an object to Ajax ({URL: '', / / requested address type: '', / / request method async: '', / / asynchronous data: '', / / parameter dataType: '', / / whether to execute json.parse success: function() {} / / function executed after success})
    
    • After determining the use method, start writing the encapsulated function

Promise

  • promise is an ES6 syntax
  • Commitment means that it is specifically used to solve the problem of asynchronous callback hell

Callback function

  • What is a callback function?

  • Is to pass function A as an argument to function B

  • Call in function B as a row parameter

    function a(cb) {
      cb()
    }
    
    function b() {
      console.log('I'm a function b')
    }
    
    a(b)
    
  • Why do I need a callback function

    • When we execute an asynchronous behavior, we need to do something after an asynchronous behavior is executed
    • So, there is no way to predict in advance when this asynchronous behavior is completed
    • We can only do it in the form of callback function
    • For example, success in the ajax function we just encapsulated
    • We don't know when the ajax request will be completed, so we need to do it in the form of callback function

Callback hell

  • When a callback function is nested with a callback function

  • A nested structure appears

  • When nested more, there will be a callback to hell

  • For example, we send three ajax requests

    • First normal transmission
    • The second request requires a value in the result of the first request as a parameter
    • The third request requires a value in the result of the second request as a parameter
    ajax({
      url: 'I'm the first one to ask',
      success (res) {
        // Now send the second request
        ajax({
          url: 'I'm the second request',
          data: { a: res.a, b: res.b },
          success (res2) {
            // Make a third request
            ajax({
              url: 'I'm the third request',
              data: { a: res2.a, b: res2.b },
      				success (res3) { 
                console.log(res3) 
              }
            })
          }
        })
      }
    })
    
  • Callback hell is actually caused by too many nested callback functions

[external link image transfer failed. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-1vIjT0GF-1626013036406)(C:/Users / simple point / Desktop / profile / assets / callback hell. jpeg)]

  • When the code becomes this structure, there is no possibility of maintenance
  • So we should write the code more artistically

PROMISE

  • To solve the callback hell

  • We will use promise syntax

  • Syntax:

    new Promise(function (resolve, reject) {
      // resolve indicates a successful callback
      // reject indicates a failed callback
    }).then(function (res) {
      // Successful function
    }).catch(function (err) {
      // Failed function
    })
    
  • promise is a grammar

    • Each of our asynchronous events is executed
    • There will be three states: executing / successful / failed
  • Because it contains successful callback functions

  • So we can use promise to solve the problem of multiple ajax sending

    new Promise(function (resolve, reject) {
      ajax({
        url: 'First request',
        success (res) {
          resolve(res)
        }
      })
    }).then(function (res) {
      // Ready to send a second request
      return new Promise(function (resolve, reject) {
        ajax({
          url: 'Second request',
          data: { a: res.a, b: res.b },
          success (res) {
            resolve(res)
          }
        })
      })
    }).then(function (res) {
      ajax({
        url: 'Third request',
        data: { a: res.a, b: res.b },
        success (res) {
          console.log(res)
        }
      })
    })
    
  • At this time, our code has changed a lot

  • Basically, it can be maintained

  • But for a programmer, this is not enough

  • We also need more simplified code

  • So we need to use an es7 syntax

  • It's called async/await

ASYNC/AWAIT (synchronous asynchronous)

  • async/await is an es7 syntax

  • This syntax is the ultimate solution to callback hell

  • Syntax:

    async function fn() {
      const res = await promise object
    }
    
  • This is a special function

  • You can await a promise object

  • Asynchronous code can be written to look like synchronous code

  • As long as it is a promiser object, we can use async/await to write

    async function fn() {
      const res = new Promise(function (resolve, reject) {
        ajax({
          url: 'First address',
          success (res) {
            resolve(res)
          }
        })
      })
      
      // res can get the requested result
      const res2 = new Promise(function (resolve, reject) {
        ajax({
          url: 'Second address',
          data: { a: res.a, b: res.b },
          success (res) {
            resolve(res)
          }
        })
      })
      
      const res3 = new Promise(function (resolve, reject) {
        ajax({
          url: 'Third address',
          data: { a: res2.a, b: res2.b },
          success (res) {
            resolve(res)
          }
        })
      })
      
      // res3 is the result we want
      console.log(res3)
    }
    
    • Such asynchronous code looks like synchronous code

Design mode

  • Design pattern is a concise and optimized solution to specific problems when we solve problems
  • We have many design patterns
    • Singleton mode
    • Combination mode
    • Observer mode
    • ...
  • Today, let's talk about these three design patterns
    • Single case mode / combination mode / observer mode

Singleton mode

  • What is singleton mode?
  • As we all know, constructors can create an object
  • We can get many objects by new constructor many times
  • Singleton mode: when using constructor instantiation, no matter how many times it is instantiated, it is the same object
    • That is, a constructor can only new out one object in a lifetime
  • In other words, when we use the constructor, we design it into the singleton mode every time the new object properties / functions / methods are exactly the same

Core code

  • The core code of singleton mode is very simple

  • In fact, it's just to judge whether he has new objects

  • If so, continue to use the previous object. If not, give you a new one

    // Prepare a constructor
    // new in the future
    function Person() {}
    
    // Prepare a singleton mode function
    // This singleton mode function makes Person a singleton mode
    // When you want new Person again in the future, just execute the singleton function
    function singleton () {
      let instance
      
      if (!instance) { // If instance has no content
        // Come here and prove that instance has no content
        // Assign him new Person
          instance = new Person()
      }
      
      // Always return the first instance of new Person
      // That is, it will always be an example
      return instance
    }
    
    const p1 = singleton()
    const p2 = singleton()
    console.log(p1 === p2) // true
    

application

  • Let's simply write a demo with this core code

    // The function of this constructor is to create a div and add it to the page
    function CreateDiv() {
        this.div = document.createElement('div')
        document.body.appendChild(this.div)
    }
    
    CreateDiv.prototype.init = function (text) {
        this.div.innerHTML = text
    }
    
    // Prepare to make this CreateDiv into singleton mode
    // Make singleton a closure function
    const singleton = (function () {
    
        let instance
    
        return function (text) {
            if (!instance) {
                instance = new CreateDiv()
            }
            instance.init(text)
            return instance
        }
    })()
    
    singleton('hello') // For the first time, a new div will appear on the page with the content of hello
    singleton('world') // The second time, there will be no new div, but the original div content will become world
    

Combination mode

  • The combination mode is to combine the startup methods of several constructors together

  • Then use a "remote control" for unified call

    class GetHome {
    
        init () {
            console.log('Got home?')
        }
    }
    
    class OpenComputer {
    
        init () {
            console.log('Turn on the computer')
        }
    }
    
    class PlayGame {
    
        init () {
            console.log('play a game')
        }
    }
    
    • The instantiation objects created by the above constructors are started in the same way
    • Then we can write these functions in combination mode
    • Then start uniformly
  • Prepare a constructor for a composite pattern

    class Compose {
        constructor () {
            this.compose = []
        }
        	
        // How to add a task
        add (task) {
            this.compose.push(task)
        }
        
        // A method of performing tasks
        execute () {
            this.compose.forEach(item => {
                item.init()
            })
        }
    }
    
  • Let's use our combined pattern constructor to combine the previous functions

    const c = new Compose()
    // Put all the tasks to be completed in the queue
    c.add(new GetHome())
    c.add(new OpenComputer)
    c.add(new PlayGame)
    
    // Direct drive task queue
    c.execute()
    // The init functions in the three objects are executed in order
    

Observer mode

  • The observer pattern is also commonly referred to as the publish subscribe pattern or the message pattern
  • The English name is Observer
  • Official explanation: when the state of an object changes, all objects that depend on it are notified and automatically updated, which solves the functional coupling between the subject object and the observer, that is, the problem of notifying other objects when the state of an object changes
  • It sounds confused, but it's not hard

An example

  • When you want to go to the bookstore to buy books, but it happens that there are no books you want to buy today
  • We can't always wait in the bookstore and leave our mobile phone to the clerk
  • When the books you need arrive, he will call you and tell you to buy them
  • After you buy the book, tell him that I bought it. Then you won't be notified if you come back later

addEventListener

  • The above example may not be very clear

  • But addEventListener is something we've all used

  • This thing is actually a standard observer model

    btn.addEventListener('click', function () {
        console.log('btn It was clicked')
    })
    
    • The above is that there is an invisible observer who observes every move of btn
    • When the btn is clicked, the corresponding function will be executed
    • We can also bind more functions
  • To put it bluntly: the observer mode is that we implement the function of an addEventListener ourselves

    • It's just that the addeventlistener has only fixed events and can only bind to dom elements
    • We can bind any event name we write and choose the trigger time ourselves

Writing code

  • First, we analyze the function

    • We need to have an observer (abstracted here as an object {})

    • There needs to be a property to store the message box (put all the events you bind in it)

    • You need an on method to add an event

    • You need an emit method to publish events (triggers)

    • You need an off method to cancel the added method

      const observer = {
          message: {},
          on: function () {},
          emit: function () {},
          off: function () {}
      }
      
    • We write it in the form of a constructor

      class Observer {
          constructor () {
              this.message = {}
          }
          
          on () {}
          
          emit () {}
          
          off () {}
      }
      
    • Now, the prototype of an observer comes out

    • Next, improve the method

ON

  • Let's write the ON method first

  • Add an event

  • Our on method needs to accept two parameters

    • Event type
    • Event handler
    class Observer {    constructor () {        this.message = {}    }        on (type, fn) {        // Judge whether the event type if (!this.message[type]) is set in the message box {/ / it proves that the event type is not in the message box. / / then we add it directly / / and let its value be an array, and then put the event handler this. Message [type] = [FN]} else in the array {/ / prove that the event type exists in the message box / / then we can directly add the event handler function to the array. This. Message [type]. Push (FN)}} emit() {} off() {}}
    

EMIT

  • The next step is to publish events

  • That is, let's execute the events we have subscribed to

  • You also need to accept two parameters

    • Type of event to trigger
    • Parameters passed to the event handler
    class Observer {    constructor () {        this.message = {}    }        on (type, fn) {        // Judge whether the event type if (!this.message[type]) is set in the message box {/ / it proves that the event type is not in the message box. / / then we add it directly / / and let its value be an array, and then put the event handler this. Message [type] = [FN]} else in the array {/ / prove that the event type exists in the message box / / then we can directly add the event handler function to the array. This. Message [type]. Push (FN)}} emit (type,... ARG) {/ / judge whether you have subscribed to this event before if (!this.message[type]) return / / if so, let's deal with the parameter const event = {type: type, Arg: Arg | {}} / / loop through all event handling functions subscribed for the current event type this message[type]. forEach(item => {            item.call(this, event)        })    }        off () {}}
    

OFF

  • Finally, remove the event

  • Is to remove the subscribed event handler

  • You also need to accept two parameters

    • Event type to remove
    • Event handler to remove
    class Observer {    constructor () {        this.message = {}    }        on (type, fn) {        // Judge whether the event type if (!this.message[type]) is set in the message box {/ / it proves that the event type is not in the message box. / / then we add it directly / / and let its value be an array, and then put the event handler this. Message [type] = [FN]} else in the array {/ / prove that the event type exists in the message box / / then we can directly add the event handler function to the array. This. Message [type]. Push (FN)}} emit (type,... ARG) {/ / judge whether you have subscribed to this event before if (!this.message[type]) Return / / if so, let's deal with the parameter const event = {type: type, Arg: Arg | {}} / / loop through all event handling functions subscribed for the current event type this message[type]. Foreach (item = > {item. Call (this, event)})} off (type, FN) {/ / judge whether you have subscribed to this event before. if (!this.message[type]) return / / if so, let's remove it again. For (let I = 0; I < this. Message [type]. Length; I + +) {const item = this. Message [type] [i] if (item === fn) {                this.message[type].splice(i, 1)                i--            }        }    }}
    
  • The above is the most basic observer model

  • Next, let's try it

Use it

const o = new Observer()// Prepare two event handling functions: function a (E) {console.log ('Hello ')} function B (E) {console.log ('World')} / / subscribe to event o.on('abc', a)o.on('abc', b) / / publish event (trigger) o.emit ('abc ',' 100 ',' 200 ',' 300 ') / / both functions execute back. / / remove event o.off('abc', 'b') / / publish event (trigger) o.emit ('abc ',' 100 ',' 200 ', 300') again //Only one a function is executed

NODE

  • node official website

  • node Chinese network

  • What is node

  • This is the explanation of node's official website

    • In fact, node is written in javascript language
    • In other words, with node, our javascript is not only a front-end language, but also a back-end language
  • Front end javascript

    • Three cores
      • ECMAScript
      • DOM
      • BOM
    • Operation content
      • browser
      • Resolve compatibility issues
  • Back end javascript (node)

    • core
      • ECMAScript
    • Operation content
      • Back end code
      • database
  • In other words, we don't need to solve the compatibility problem of node, DOM and BOM, and just focus on business logic

Download node installation package

  • Our computer does not have its own node environment

  • We need to manually download a node installation package to install the node environment

  • With the node environment, we can run node

  • Download method

    • Directly to node official website perhaps node Chinese network

    • Click download

      [the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-ooa2hby-1626013036406) (C: / users / simple point / Desktop / profile / assets/node download. png)]

    [the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-kyNIz2uQ-1626013036406)(C:/Users / simple point / Desktop / profile / assets/node Chinese network download. png)]

  • Note: when downloading from node Chinese network, select the installation package instead of binary files

    • Because the binary file is a simple version, we need to configure our own environment variables before we can use it

Install node environment

  • After downloading, we directly double-click the downloaded file to run it

  • Find node-v10 16.2-x64. MSI corresponding file

    [the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-1PfL2LVI-1626013036407)(C:/Users / simple point / Desktop / profile / assets/node installation 01.png)]

    [the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-RjpGAZ6G-1626013036407)(C:/Users / simple point / Desktop / profile / assets/node installation 02.png)]

    [external link image transfer failed. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-q5N8AZ6v-1626013036408)(C:/Users / simple point / Desktop / profile / assets/node installation 03.png)]

    [the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-ZlR1nSHh-1626013036408)(C:/Users / simple point / Desktop / profile / assets/node installation 04.png)]

    [the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-1ydf9ep-1626013036409) (C: / users / simple point / Desktop / profile / assets/node installation 05.png)]

    [the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-s7AzAGbG-1626013036409)(C:/Users / simple point / Desktop / profile / assets/node installation 06.png)]

  • At this time, the node is installed

Detect installation environment

  • Check whether the installation is successful

  • We open the run window (win + r)

    • It's the windows key + r key under our keyboard

      [external link picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-uFaz9agL-1626013036409)(C:/Users / simple point / Desktop / profile / assets / running window. png)]

  • Write cmd and press enter to our command line

    [external chain image transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-W9sIIBa1-1626013036410)(C:/Users / simple point / Desktop / profile / assets / command line. png)]

  • Then write an instruction to the command line

    $ node -v
    
  • Then press enter to get the version number of a node

  • Seeing the version number indicates that the node environment has been successfully installed

    [the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-OHSz8iLx-1626013036410)(C:/Users / simple point / Desktop / profile / assets/node version detection. png)]

  • So far, we have a node environment

  • Then we can run our node in the computer

node initial experience

  • By now, our node environment has been installed
  • Next, let's experience node
  • What exactly is our node
    • Is to run js code directly in the terminal (command line)
    • It can also be used js file to write a pile of js code
    • Then, without a browser, let the js code we write run on the terminal of our own computer

Write js code directly in the terminal

  • Open command line

  • Writing instructions

    $ node
    
  • Press enter directly, you will see the cursor flashing, and we enter the node coding environment

  • Just write the code directly

    [the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-AM4v74Ng-1626013036411)(C:/Users / simple point / Desktop / personal data / assets / command line directly write js code. png)]

Run a js file on the command line

  • Create a new folder first

  • Write a js file in it

    • My default here is in the desktop / demo folder / idnex js
  • Write some js code in the file

    // index.js
    console.log('hello node')
    
  • Open the command line and make the path of the command line consistent with the directory where you store the js file to be executed

    [external chain image transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-9bjzisz-1626013036411) (C: / users / simple point / Desktop / profile / assets / run js file. PNG from the command line)]

  • After switching, we directly use the instruction to run the js file we have prepared

    $ node index.js
    
  • Then we will run the js file we just wrote on the command line

  • hello node will be output on the console

    [the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-eUv9aCKD-1626013036411)(C:/Users / simple point / Desktop / profile / assets / run js file 02. PNG from the command line)]

  • Now we have run a section of js code on the command line

  • This explains what the official website said at the beginning

    • Node.js is a JavaScript running environment based on Chrome V8 engine.
      • After installing our node, we provide a running environment based on Chrome V8 engine on the command line
      • Run javascript code in this environment
      • This is node js

Common LINUX operations

  • What is LINUX operation
  • In fact, it is to use instructions on the command line to operate our computer
  • Because our node is running js on the command line
  • So we need to know some common command line instructions

Directory operation

  • Directory operation is to operate our command line path

    1. View all files in the current directory

      # windows command
      $ dir
       
      # mac command
       $ ls
      
    2. All files in the current directory and all files in subdirectories are displayed in a tree structure

    windows command

    $ tree

    mac command

    $ find . -print | sed -e 's;[^/]*/;|;g;s;|; |;g'

    3. Enter a directory under the current directory
    
    ```shell
    $ cd Folder name
    
    1. Return to the previous directory

      $ cd ..
      
    2. Switch drive letter

      $ Drive letter:$ d:
      

File operation

  • File operation is to create files or folders through instructions

    1. create folder

      # Means to create a folder called test in the current directory $mkdir test
      
    2. Remove Folder

      # Indicates that the file under the current folder is removed test folder# windows command $ rd test# Force deletion of non empty folders $ rd /s/q test# mac command $ rmdir test# Force deletion of non empty folder $rm -rf test
      
    3. Copy folder

      # Represents a copy test The folder is named test2 # windows command $ xcopy test test2# mac command $cp -R test test2
      
    4. create a file

      # Means to create a file called index.js File# windows command $ type nul> index.js # mac command $touch AAA txt
      
    5. Copy a file

     # Represents a copy index.js The file is named ceshi.js# windows command  $ copy index.js ceshi.js    # mac command $CP index js ceshi. js
    
  1. Write content to text

    # Express to index.js Write a text in console.log('hello world')# windows command  $ echo console.log("hello world")>index.js  # mac command  $ vim index.js # Just enter the editing mode and write directly  # After editing, press esc and then: wq save and exit
    
  2. View the text content in the file

    # Indicates view index.js What is the text content in the file# windows command $ type index.js# mac command $open index js
    
  3. Rename a file or directory

    # Express handle index.js Renamed abc.js# windows command $ ren index.js abc.js# mac command $MV index js abc. js
    
  4. Delete file

    # Indicates that the current directory index.js delete# windows command $ del index.js# mac command $RM ABC js
    
  5. move a file or folder

    # Indicates that the current directory index.js Move files to the current directory a Under folder# windows command  $ move index.js a# mac command $MV index js a
    

Other instructions

  • Used when doing something else

    1. Clear screen

      # Indicates that all contents of the current screen are cleared# windows command $cls
      

    mac command

    $ clear

    2. View current PC IP information   ```shell # Indicates to view the current computer IP information      # window command   $ ipconfig    # mac command $ifconfig
    
    1. Test the network speed of a link address

      # Indicates the speed of viewing and visiting Baidu website $ping www.baidu.com com
      
    2. View computer information

      # Indicates to view information about the current computer# windows command $ systeminfo# mac command $system_prefiler
      

Import and export of NODE

  • The development of node is modular development
  • Each js file is an independent module
  • Each has its own independent scope
  • We can combine multiple js files by importing and exporting

Import

  • In node, we use require to import a file

    // I'm index JS file require ('. / A.js') console Log ('I am the index.js file ')
    
  • When I run index. On the command line JS file

    • First, the a.js file will be run again
    • Then continue to execute the code inside my own file
  • You can also accept the contents exported from another file when importing again

    // The content received by a is the content exported from the a.js file. / / if nothing is exported from the a.js file, an empty object const a = require('./a.js') is received
    

export

  • When we write a js file, we can export some content

  • In the future, when this file is imported, some content can be accepted

    // I am a.js / / every JS file will have an object called module / / there is a member called exports in the module / / every JS file will default to module Exports / / that is, we export to module What content is added to exports / / then what content module will be exported exports. name = 'Jack'module.exports. age = 18
    
  • When this file is imported in the future, the received content is an object with two members

    // I'm index jsconst a = require('./a.js')console. log(a) // { name: 'Jack', age: 18 }
    

modularization

  • During the development of node
  • We make each function into a module independently
  • Then they are linked together by importing and exporting
    • Conducive to maintenance
    • Accurate positioning
  • We generally divide modules into three types
    1. Built in module (a module that node is born with)
    2. Custom module (our own file)
    3. Third party modules (modules written by others downloaded from the Internet)

Common built-in modules of NODE

  • We just wrote the module ourselves
  • Now let's talk about common built-in modules

FS module

  • fs is a built-in module of node

  • Designed to manipulate files

  • When using, you can import it directly

    const fs = require('fs')// Next, you can use the fs variable to manipulate the file
    

Read file contents asynchronously

  • Read the contents of a file asynchronously

    const fs = require('fs')// Because it is read asynchronously, the result FS should be obtained in the callback function Readfile ('. / text. TXT', 'utf8', function (err, data) {/ / err indicates an error occurred during reading. / / data indicates the read content. If an error occurs, data has no content})
    

Read file contents synchronously

  • Read the contents of a file synchronously

    const fs = require('fs')// Because it is a synchronous read, you can const res = FS by directly receiving the read content in the form of return value Readfilesync ('. / text. TXT','utf8 ') / / if an error occurs during synchronous reading, an error will be reported directly on the console and the program will be interrupted to continue. / / if there is no error, res will get the contents of the file
    

Write file asynchronously

  • Write content to a file asynchronously

    const fs = require('fs')// Generally, there is no error when writing content. / / if there is no such file, a file will be created to write content to it. / / so the callback function is generally useless. It is just to do something after writing the file. / / although it is useless, it must be written to FS WriteFile ('. / text. TXT', 'I want to write', function() {console. Log ('write complete ')})
    

Synchronous write file

  • Synchronous writing to a file

    const fs = require('fs')// Because it is written to the file. / / no value is returned, because it is generally written to FS Writefilesync ('. / text. TXT', 'I want to write')
    

HTTP module

  • Because node is a server language

  • Therefore, node can also start a server and a service

  • The http module is specifically used to start the service, accept the request and return the response

  • http is also a built-in module, which can be imported and used directly

    const http = require('http')// Next, you can use the http module to start the service
    

Create a service

  • To start, you need to create a service

    const http = require('http')// Create a service. / / the service listens to the HTTP protocol by default. / / the service listens to the localhost domain name by default. / / the returned value is the service const server = http Createserver (function (request, response) {/ / this function is triggered for every request sent from the front end. / / request contains all the request information. / / response is all the response information})
    

Listen on a port

  • Determine which port this service listens to

    const http = require('http')// Create a service const server = http Createserver (function (request, response) {/ / every request from the front end will trigger this function}) server Listen (8080, function() {/ / this function will execute console.log ('linking on port 8080 ')} after the service is started successfully
    

Give a response

  • Give a simple response

    const http = require('http')// Create a service const server = http Createserver (function (request, response) {/ / this function is triggered for every request sent from the front end. / / a response response. End ('Hello world ')} is given after receiving the request Listen (8080, function() {/ / this function will execute console.log ('linking on port 8080 ')} after the service is started successfully
    
  • The browser opens

  • Enter localhost:8080 in the address bar

  • The browser will respond with the text hello world

NPM

  • When we install the node environment, it will automatically help us install an npm environment together

  • It's like when we install some software, we will automatically install some XXX software Housekeeper / xxx games for us

  • But npm is not junk software, but a super practical tool

Check whether it is installed

  • It is the same as detecting node

  • Enter instructions on the command line

    $ npm -v
    
  • Just get a version number

Understanding npm

  • What is npm
  • We can think of it as a big supermarket, a supermarket with all the plug-ins / libraries / frameworks we need
  • We want to download a jQuery validation plug-in
    • We can choose to download on the official website
    • You can choose to go to GitHub to find and download
    • You can also choose to download directly from the command line with npm
  • We want to download a bootstrap
    • We can choose to go to the official website to download
    • You can choose to go to GitHub to find and download
    • You can also choose to download directly from the command line with npm
  • In other words, npm contains all our third-party things
  • When we need it, as long as we open the terminal, we can use instructions to help us download it
    • You don't need to go to the official website anymore
  • Moreover, npm can be used not only at the back end, but also at the front end
  • npm is just a large package manager that depends on the node environment

Using npm

  • If we want to use npm, just open the command line
  • As a package manager
  • You can download some plug-in library frameworks for us to use

Download package

  • Open command line

  • Enter the download instructions

    # Means to use npm to download a jQuery $npm install jQuery
    
  • After downloading, one more folder will be added to the current directory

    • It's called node_modules
    • In this directory, there will be a folder called jquery
    • That's what we need
  • npm downloads the latest version of the package by default

  • We can also specify which version I want to download when downloading

    # Means to use npm to download a 3.3.7 version of jQuery $npm install bootstrap@3.3.7
    

Delete package

  • When deleting a package, we can go directly to node_ Find the corresponding package folder in the modules folder and delete it

  • However, this is not good. We should still use the command line instructions to delete the package

    # Indicates that I want to delete the jquery package $npm uninstall jquery
    
  • In this way, the package will be uninstalled

Management project

  • Each of our projects may need to rely on many packages (plug-ins / libraries / frameworks)

  • npm will help us record the packages we are currently using for this project

  • But the premise is that you should tell npm, "you can help me manage the whole folder."

  • We still use instructions to tell npm on the command line

    # Tell npm to help us manage the whole folder (that is, my whole project) $npm init
    

npm clear cache

  • Sometimes, some packages fail to download halfway because of various reasons (for example, there is no Internet suddenly)

  • Then the half downloaded package may be cached

  • Then when you download again in the future, it will be in the state of failure

  • Then we have to clear the cache and download again

    # Indicates to clear npm cache $npm cache clear -f
    

NRM

  • Although our npm is easy to use
  • But there is one drawback
    • Yes, although he's downloading things for us
    • But his download address is abroad
    • In other words, every time you use npm to download, you go to a foreign server to download
    • Then there will be many unstable factors
    • And the relative time is relatively long
  • nrm is a tool used to switch npm download addresses (switch image source tool)

Install the NRM

  • If we want to use nrm, we need to install it ourselves

  • Because it is our tool, it can be installed using npm

  • It is still installed by using instructions

  • It's just that the nrm should be installed as a global dependency instead of a dependency within the project

    • Global dependency. A computer can always be used after it is installed once
  • We use the command to install a global nrm

    # Indicates to install a global NRM $NPM install -- global NRM
    

Test installation

  • After the installation, let's check whether the installation is successful

  • The same as when detecting node npm

  • Check the version number on the command line using the command

    $ nrm --version
    
  • If the version number appears, the installation is successful

Use nrm

  • There are several image source addresses in nrm
  • We need to pick a faster one to use

Detect mirror source address

  • We directly use the command line to check the network speed of all image source addresses

    # Indicates viewing nrm image source address network speed $nrm test
    

Switch mirror source

  • After we finish the test, we will wait until which is faster

  • Let's use the command to switch the image source address

    # Indicates switching to taobao image source address $nrm use taobao
    

st2# mac command $cp -R test test2
```

  1. create a file

    # Means to create a file called index.js File# windows command $ type nul> index.js # mac command $touch AAA txt
    
  2. Copy a file

 # Represents a copy index.js The file is named ceshi.js# windows command  $ copy index.js ceshi.js    # mac command $CP index js ceshi. js
  1. Write content to text

    # Express to index.js Write a text in console.log('hello world')# windows command  $ echo console.log("hello world")>index.js  # mac command  $ vim index.js # Just enter the editing mode and write directly  # After editing, press esc and then: wq save and exit
    
  2. View the text content in the file

    # Indicates view index.js What is the text content in the file# windows command $ type index.js# mac command $open index js
    
  3. Rename a file or directory

    # Express handle index.js Renamed abc.js# windows command $ ren index.js abc.js# mac command $MV index js abc. js
    
  4. Delete file

    # Indicates that the current directory index.js delete# windows command $ del index.js# mac command $RM ABC js
    
  5. move a file or folder

    # Indicates that the current directory index.js Move files to the current directory a Under folder# windows command  $ move index.js a# mac command $MV index js a
    

Other instructions

  • Used when doing something else

    1. Clear screen

      # Indicates that all contents of the current screen are cleared# windows command $cls
      

    mac command

    $ clear

    2. View current PC IP information   ```shell # Indicates to view the current computer IP information      # window command   $ ipconfig    # mac command $ifconfig
    
    1. Test the network speed of a link address

      # Indicates the speed of viewing and visiting Baidu website $ping www.baidu.com com
      
    2. View computer information

      # Indicates to view information about the current computer# windows command $ systeminfo# mac command $system_prefiler
      

Import and export of NODE

  • The development of node is modular development
  • Each js file is an independent module
  • Each has its own independent scope
  • We can combine multiple js files by importing and exporting

Import

  • In node, we use require to import a file

    // I'm index JS file require ('. / A.js') console Log ('I am the index.js file ')
    
  • When I run index. On the command line JS file

    • First, the a.js file will be run again
    • Then continue to execute the code inside my own file
  • You can also accept the contents exported from another file when importing again

    // The content received by a is the content exported from the a.js file. / / if nothing is exported from the a.js file, an empty object const a = require('./a.js') is received
    

export

  • When we write a js file, we can export some content

  • In the future, when this file is imported, some content can be accepted

    // I am a.js / / every JS file will have an object called module / / there is a member called exports in the module / / every JS file will default to module Exports / / that is, we export to module What content is added to exports / / then what content module will be exported exports. name = 'Jack'module.exports. age = 18
    
  • When this file is imported in the future, the received content is an object with two members

    // I'm index jsconst a = require('./a.js')console. log(a) // { name: 'Jack', age: 18 }
    

modularization

  • During the development of node
  • We make each function into a module independently
  • Then they are linked together by importing and exporting
    • Conducive to maintenance
    • Accurate positioning
  • We generally divide modules into three types
    1. Built in module (a module that node is born with)
    2. Custom module (our own file)
    3. Third party modules (modules written by others downloaded from the Internet)

Common built-in modules of NODE

  • We just wrote the module ourselves
  • Now let's talk about common built-in modules

FS module

  • fs is a built-in module of node

  • Designed to manipulate files

  • When using, you can import it directly

    const fs = require('fs')// Next, you can use the fs variable to manipulate the file
    

Read file contents asynchronously

  • Read the contents of a file asynchronously

    const fs = require('fs')// Because it is read asynchronously, the result FS should be obtained in the callback function Readfile ('. / text. TXT', 'utf8', function (err, data) {/ / err indicates an error occurred during reading. / / data indicates the read content. If an error occurs, data has no content})
    

Read file contents synchronously

  • Read the contents of a file synchronously

    const fs = require('fs')// Because it is a synchronous read, you can const res = FS by directly receiving the read content in the form of return value Readfilesync ('. / text. TXT','utf8 ') / / if an error occurs during synchronous reading, an error will be reported directly on the console and the program will be interrupted to continue. / / if there is no error, res will get the contents of the file
    

Write file asynchronously

  • Write content to a file asynchronously

    const fs = require('fs')// Generally, there is no error when writing content. / / if there is no such file, a file will be created to write content to it. / / so the callback function is generally useless. It is just to do something after writing the file. / / although it is useless, it must be written to FS WriteFile ('. / text. TXT', 'I want to write', function() {console. Log ('write complete ')})
    

Synchronous write file

  • Synchronous writing to a file

    const fs = require('fs')// Because it is written to the file. / / no value is returned, because it is generally written to FS Writefilesync ('. / text. TXT', 'I want to write')
    

HTTP module

  • Because node is a server language

  • Therefore, node can also start a server and a service

  • The http module is specifically used to start the service, accept the request and return the response

  • http is also a built-in module, which can be imported and used directly

    const http = require('http')// Next, you can use the http module to start the service
    

Create a service

  • To start, you need to create a service

    const http = require('http')// Create a service. / / the service listens to the HTTP protocol by default. / / the service listens to the localhost domain name by default. / / the returned value is the service const server = http Createserver (function (request, response) {/ / this function is triggered for every request sent from the front end. / / request contains all the request information. / / response is all the response information})
    

Listen on a port

  • Determine which port this service listens to

    const http = require('http')// Create a service const server = http Createserver (function (request, response) {/ / every request from the front end will trigger this function}) server Listen (8080, function() {/ / this function will execute console.log ('linking on port 8080 ')} after the service is started successfully
    

Give a response

  • Give a simple response

    const http = require('http')// Create a service const server = http Createserver (function (request, response) {/ / this function is triggered for every request sent from the front end. / / a response response. End ('Hello world ')} is given after receiving the request Listen (8080, function() {/ / this function will execute console.log ('linking on port 8080 ')} after the service is started successfully
    
  • The browser opens

  • Enter localhost:8080 in the address bar

  • The browser will respond with the text hello world

NPM

  • When we install the node environment, it will automatically help us install an npm environment together

  • It's like when we install some software, we will automatically install some XXX software Housekeeper / xxx games for us

  • But npm is not junk software, but a super practical tool

Check whether it is installed

  • It is the same as detecting node

  • Enter instructions on the command line

    $ npm -v
    
  • Just get a version number

Understanding npm

  • What is npm
  • We can think of it as a big supermarket, a supermarket with all the plug-ins / libraries / frameworks we need
  • We want to download a jQuery validation plug-in
    • We can choose to download on the official website
    • You can choose to go to GitHub to find and download
    • You can also choose to download directly from the command line with npm
  • We want to download a bootstrap
    • We can choose to download on the official website
    • You can choose to go to GitHub to find and download
    • You can also choose to download directly from the command line with npm
  • In other words, npm contains all our third-party things
  • When we need it, as long as we open the terminal, we can use instructions to help us download it
    • You don't need to go to the official website anymore
  • Moreover, npm can be used not only at the back end, but also at the front end
  • npm is just a large package manager that depends on the node environment

Using npm

  • If we want to use npm, just open the command line
  • As a package manager
  • You can download some plug-in library frameworks for us to use

Download package

  • Open command line

  • Enter the download instructions

    # Means to use npm to download a jQuery $npm install jQuery
    
  • After downloading, one more folder will be added to the current directory

    • It's called node_modules
    • In this directory, there will be a folder called jquery
    • That's what we need
  • npm downloads the latest version of the package by default

  • We can also specify which version I want to download when downloading

    # Means to use npm to download a 3.3.7 version of jQuery $npm install bootstrap@3.3.7
    

Delete package

  • When deleting a package, we can go directly to node_ Find the corresponding package folder in the modules folder and delete it

  • However, this is not good. We should still use the command line instructions to delete the package

    # Indicates that I want to delete the jquery package $npm uninstall jquery
    
  • In this way, the package will be uninstalled

Management project

  • Each of our projects may need to rely on many packages (plug-ins / libraries / frameworks)

  • npm will help us record the packages we are currently using for this project

  • But the premise is that you should tell npm, "you can help me manage the whole folder."

  • We still use instructions to tell npm on the command line

    # Tell npm to help us manage the whole folder (that is, my whole project) $npm init
    

npm clear cache

  • Sometimes, some packages fail to download halfway because of various reasons (for example, there is no Internet suddenly)

  • Then the half downloaded package may be cached

  • Then when you download again in the future, it will be in the state of failure

  • Then we have to clear the cache and download again

    # Indicates to clear npm cache $npm cache clear -f
    

NRM

  • Although our npm is easy to use
  • But there is one drawback
    • Yes, although he's downloading things for us
    • But his download address is abroad
    • In other words, every time you use npm to download, you go to a foreign server to download
    • Then there will be many unstable factors
    • And the relative time is relatively long
  • nrm is a tool used to switch npm download addresses (switch image source tool)

Install the NRM

  • If we want to use nrm, we need to install it ourselves

  • Because it is our tool, it can be installed using npm

  • It is still installed by using instructions

  • It's just that the nrm should be installed as a global dependency instead of a dependency within the project

    • Global dependency. A computer can always be used after it is installed once
  • We use the command to install a global nrm

    # Indicates to install a global NRM $NPM install -- global NRM
    

Test installation

  • After the installation, let's check whether the installation is successful

  • The same as when detecting node npm

  • Check the version number on the command line using the command

    $ nrm --version
    
  • If the version number appears, the installation is successful

Use nrm

  • There are several image source addresses in nrm
  • We need to pick a faster one to use

Detect mirror source address

  • We directly use the command line to check the network speed of all image source addresses

    # Indicates viewing nrm image source address network speed $nrm test
    

Switch mirror source

  • After we finish the test, we will wait until which is faster

  • Let's use the command to switch the image source address

    # Indicates switching to taobao image source address $nrm use taobao
    

Topics: Javascript