Self study JS note taking knowledge (there may be errors, welcome to correct)

Posted by markjoe on Fri, 21 Jan 2022 09:02:09 +0100

Common browsers

  • webkit kernel (v8) engine

    • google chrome
    • safari
    • opera(v14)
    • Domestic browser
    • Mobile phone browser
    • ...
  • Gecko

    • Firefox Firefox
  • presto

    • opera <v14
  • Trident

    • IE
    • Ie edge (starting with dual core)

JS as client language

  • Operate the elements in the page according to the relevant syntax, and sometimes operate the browser
  • ECMAScript3/5/6...: syntax specification of JS
  • DOM (document object model): provide some JS properties and methods to manipulate DOM elements in the page
  • BOM (browser object model): provides some JS properties and methods to operate the BOM elements of the browser

variable in JS

Variable: variable quantity, in programming language, is a name used to store and represent things with different values

//ES3
var a = 12;
a = 13;
console.log(a);//The output is a with a value of 13

//ES6
let b = 100;
b = 200;

const c = 1000;
c = 2000;//An error is reported because the value created by const cannot be modified (it can be understood as a constant)
=========================================
``**however**``If const The defined object is a reference data type,be const The value of the reference type can be changed only when the pointer remains unchanged
=========================================

// const person = {
     name : 'Lao Wang',
     sex : 'male'
 }
 
 person.name = 'Lao Li'
 
 console.log(person.name)//Export Lao Li

person = {
   name : 'test',
   sex : 'male'
}//An error will be reported

//Creating a function is also equivalent to creating a variable
function fn(){}
//Creating a class is also equivalent to creating a variable
class A{}
//The module import of ES6 is also equivalent to creating variables
import B from './B.js'
//Symbol creates a unique value
let n = Symbol(100);
let m = Symbol(100);
n==m;//false will be returned

Naming conventions in JS

  • Strictly case sensitive
  • Use numbers, letters, underscores, $, numbers cannot begin
let $box//Generally, jquery is used to get information starting with $
let _box//General public variables are_ start
  • Hump naming method: the first letter is lowercase, and the first letter of each other word is capitalized (naming shall be semantic as much as possible)
  • Keywords and reserved words cannot be used

Common data types in JS

  • Basic data type
    • number
      General digital and NAN
    • String string
      All enclosed in single quotation marks, double quotation marks and back quotation marks are strings
    • Boolean
      true and false
    • Null object pointer null
    • Type undefined is not defined
  • Reference data type
    • Object data type object
      • {} normal object
      • [] array object
      • /^$/ regular object
      • Math function object
      • Date object
      • ...
    • Function data type function

Number number type

Including: regular number, NaN

NaN

Not a number: is not a number, but belongs to the number type
NaN is not equal to any value (including yourself), NaN= NaN, so we can't judge whether it is a significant number in an equal way

isNaN

Check whether a value is a non valid number. If it is not a valid number, return true; otherwise, return false

When using isNaN to detect, first verify whether the detected value is of digital type. If not, first convert the value to digital type based on the Number() method, and then detect
ex:console.log(isNAN('10 ') / / returns false. First, Number('10') becomes 10, and IsNaN (10) returns false
ex1:console.log(isNaN('AA ') / / first change Number('AA') to NaN, and then isNaN(NaN). The result returns true

Use Number() to convert

  • String to number

console.log(Number('12.5 ') / / the result is 12.5
console.log(Number('12.5px ') / / the result is NaN
console.log(Number('12.5.0 ') / / the result is NaN
console.log(Number(')) / / an empty string returns 0. Note that an empty string is not equal to a space

  • Boolean to digit

console.log(Number(true)) / / the result is 1
console.log(Number(false)) / / the result is 0
console. Log (number (isNaN(true)) / / the result is also 0. The process is to first judge isNaN(true), change true to 1 with Number(true), and then isNaN(1). It returns false. The result is that Number(false) returns 0
console.log(isNan(true)) / / the result returns false

  • Null pointer type to number

console.log(Number(null)) / / the result is 0

  • Undefined type to number

console.log(Number(undefined)) / / the result is NaN

  • Convert the reference data type to a number. / / convert the reference data type to a number. Use the toString method to convert the reference data type to a string, and then to a number

console.log(Number({})) / / the result is NaN. The process starts with ({}) toString() is converted to "[object]", and then number ("[object]") returns NaN
console.log(Number([]) / / the result is 0. In the process, first convert the array to "" using toString(), then Number(""), and the result returns 0
console.log(Number([10]) / / the result is 10
console.log(Number([1,2]) / / the result is NaN

Number() bottom mechanism summary

Number() converts other data types into numbers according to the browser's underlying mechanism
String: check whether it contains non valid numeric characters. The result is NaN, where the "" result is 0
Boolean: true - > 1 false - > 0
null->0
undefined->NaN
All reference type values must be converted to strings before being converted to numbers

  • {} / regular / function, etc. - > Nan
  • []->""->0
  • ["12"]->"12"->12
  • [12,13]->"12,13"->NaN
  • ...

Use parseInt() and parseFloat()

  • They are all converted to numeric types, but they are specifically for string search. The rule is to search for valid digits from left to right until non valid numeric characters are encountered, and the search will be stopped (no matter whether there are valid digits or not)

parseInt/Float() conversion mechanism

They all follow the mechanism of searching from left to right according to the string to find valid numeric characters (so the passed value must be a string. If it is not a string, it must be converted to a string and then searched)
parseInt(undefined)->parseInt("undefined")->NaN
ParseInt ("") - > Nan (because no valid number is found, 0 will be returned if it is the Number() method)

Compare with = =

  • '10' = = 10 / / the result returns true and converts the string '10' to the number 10

String string numeric type

All enclosed in single quotation marks, double quotation marks and back quotation marks are strings

Converts other types of values to strings

  • [val].toString() / / note that null and undefined cannot directly toString, ordinary objects {} ToString is not directly quoted, but becomes "[object]"
  • String splicing
    console.log('10 '+ 10) / / the output result is 1010
    console.log('10 '- 10) / / the output result is 0
    console.log('10px '- 10) / / the output result is NaN. The' 10px 'will be converted to NaN by the browser bottom layer using the Number() method, and then the operation will be performed
    ex:
    let a = 10 + null + true + [] + undefined + 'hello' + null + [] + 10 + false
    console.log(a)
    //10 + null ->10
    //10 + true ->11
    //11 + [] ->11 + '' ->'11'
    //'11' + undefined -> '11undefined'
    //'11undefined' + 'hello' - > '11undefined Hello'
    //'11undefined Hello' + null - > '11undefined Hello null'
    //'11undefined Hello null' + [] - > '11undefined Hello null'
    //'11undefined Hello null' + 10 - > '11undefined Hello null10'
    //'11undefined Hello null10' + false - > '11undefined Hello null10false'

boolean data type

There are only two values, true and false

Other data types are converted to boolean

All values are true except 0, NaN, '', null and undefined (without any special circumstances)

Conversion method

  • Boolean(val)
  • !/!!
  • Conditional judgment
if(1){
   console.log("Hello");
 }//1 convert boolean type to true, then output

 if('3px' + 3){
   console.log("Hello");
 }//String splicing of '3px' + 3 to '3px3', then converted to Boolean value of true, and finally output

 if('3px - 3'){
   console.log("Hello");
 }//'3px' - 3 performs four operations, the result is NaN, and then converted to Boolean is false, and the result is not output
**`ex:`**
console.log(Boolean(0))//false
console.log(Boolean(''))//false
console.log(Boolean(' '))//true
console.log(Boolean(null))//false
console.log(Boolean(undefined))//false
console.log(Boolean([]))//true
console.log(Boolean([10]))//true
console.log(Boolean(-1))//true
console.log(!1)//If the result is false, it will be converted to Boolean first, and then negative
console.log(!!1)//The result is true,!! Taking negation and then taking negation is equal to not taking negation, but turning to Boolean

null and undefined

All said no

  • Null is generally expected (you don't know the value at first, set it to null manually, and assign it later)
let num = null;//A variable is defined and assigned null
  • undefined is usually unexpected
let num;//If a variable is defined without assignment, it is undefined by default

Object data type - normal object

{[key]:[value],...} any object is composed of zero to multiple key value pairs (attribute name: attribute value), and the attribute name cannot be repeated
Method to get object:

  • Object Attribute name / object [attribute name]
let person = {
  name:'Xiao Wang',
  age:'20',
  sex:'boy',
  height:'185cm',
  1:'100 branch'
} //person.name/person['name '] can get the name attribute

  • If the obtained property name does not exist, it defaults to undefined
console.log(person.weight)//The result is undefined
  • If the attribute name in an object is a number, the object cannot be used Property name
console.log(person['1'])//Output 100 points
console.log(person.1)//Syntax error SyntaxError
  • Add attribute value
person.girlFriend = 'Xiaoyu'
console.log(person.girlFriend)//Output Xiaoyu
  • Delete attribute value
    • False deletion (the attribute is still in use and the value is empty):
    person.name = 'null'//Set the name attribute in person to null
    
    • Really delete (properties are gone)
    delete person['1']//Delete this 1 attribute in person
    

Object data type - array object

Arrays are special object data types

let ary = [10,20,'Hello',true]//Equivalent to the following
let ary = {
  0:10,
  1:20,
  2:'Hello',
  3:true,
  length:4
}//Therefore, the contents we write in the array are attribute values, and the attribute names of the array are incremented from 0

Index array

console.log(ary.length-1)//Index the contents of the last element of the array
console.log(ary[0])//Index the contents of the first element of the array

Add array contents

ary[ary.length] = 5;//Add an attribute value of 5 at the end of the array, and the length of the array increases automatically
console.log(ary);

Difference between basic type and reference type

Basic types operate by value
Reference types operate by reference address
ex:

	let a =12;
    let b = a;
    b = 13;
    console.log(a);//Output 12

    let n = {
        name:"boy"
    }

    let m = n;
    m.name = "girl";
    console.log(n.name);//Output girl

Data type detection in JS

  • typeof [val]: operator used to detect data type. It is not a function
    • Based on the results of typeof detection

    1. The first is a string
    2. The string contains the corresponding type

    • typeof limitations

    1. Typeof null = > "object", but null is not an object
    2. Based on typeof, it is impossible to subdivide whether the current value is an ordinary object or an array object, because as long as it is an object data type, the returned result is "object"
    ex:

    console.log(typeof typeof typeof [])//The output result is "string", the return result of the innermost typeof [] is "object", and the outer typeof is detected as "string"
    
  • instanceof: used to detect whether the current instance belongs to an instance of a class
  • constructor: detects data types based on constructors (also class based methods)
  • Object.prototype.toString.call(): the best way to detect data types

Operation statements in JS: judgment and loop

judge

What do you do when the conditions are established? What if the conditions are not established?

  • if/elseif/else
  • Ternary operator

Conditions? Things handled when conditions are established: things handled when conditions are not established
If you deal with more things, wrap them in parentheses, and separate everything with commas
If you don't need to handle things, use null or undefined to occupy the space

let a = 10;
a >=0 && a<20 ? (a++,console.log(a)):null
  • switch case

Different operations of a variable with different values
At the end of each case, it's best to add break. Without break, the following conditions will be executed whether they are true or not until a break is encountered
Each case is compared with = = = "absolute equality", while the case of ifelse is compared with = = = "equality"
=========================================================

  • Compare with =

==: equal (if the data types on both sides are different, they will be converted to the same data type and then compared)
=: absolute equality (if the types on both sides are different, they must be different, and the data type will not be converted by default). In order to ensure business rigor in the project, it is recommended to use=

Double equal sign = =:

(1) If the two values are of the same type, compare them with three equal signs (= = =)

(2) If the two value types are different, they may also be equal. Type conversion and comparison shall be carried out according to the following rules:

1) If one is null and the other is undefined, then it is equal

2) If one is a string and the other is a numeric value, convert the string into a numeric value and compare it

Equal sign = =:

(1) If the types are different, they must not be equal

(2) If both are numerical values and are the same value, they are equal; If at least one of them is NaN, it is not equal. (to judge whether a value is NaN, you can only use isNaN())

(3) If both are strings and the characters in each position are the same, they are equal, otherwise they are not equal.

(4) If both values are true or false, they are equal

(5) If both values refer to the same object or function, they are equal, otherwise they are not equal

(6) If both values are null or undefined, they are equal

=======================================================

let b= 1;
switch(b){
  case 1:
    console.log('Event with execution condition 1');
    break;
  case 2:
    console.log('Event with execution condition 2');
    break;
  case 3:
    console.log('Event with execution condition 3');
    break;
  default:
    console.log('Event executed when none of the above conditions are met');
}//The output result is' event with execution condition 1 '

//When different conditions need to do the same thing, it can be realized without break
switch(num){
  case 1:
  case 2:
    num++;
    break;
  default:
  console.log(num);
}//This code enables num + + to be executed when num=1 and num=2

Difference between i + + and + + i (difference between i + + and i+=1 and i=i+1)

i + + is to take the value for operation first, and then increase it by itself
++i is to automatically increase the value first, and then calculate the value after self increase
i + + is purely mathematical calculation, while i+=1 and i=i+1 will be spliced if i is a string

**ex:**

let i="10";
i=i+1;// => i="101"
i+=1// => i="101"
i++// => i="11"

i – difference from -- i

The difference is the same as i + + and + + i, but there is no difference between i-=1 and i=i-1, because the subtraction operation only has numerical operation

Simple DOM element operation

The traditional way of operating DOM realizes business requirements
1. Get who you want to operate first
2. Bind an event to an element
3. What to do when the event is triggered

  • document.getElementById([ID]): get the current element object through the element ID in the whole document
  • Element object onxxx=function() {}: represents event binding, xxx event type (click/mouseover/mousedown/keydown...)
  • Element object style.xxx=xxx: modify a style value of an element
    ex:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Mouse click</title>
</head>
<style>
    *{
        margin: 0;
        padding: 0;
    }
    .box{
        width: 200px;
        height: 40px;
        box-sizing: border-box;
        line-height: 40px;
        text-align: center;
        border: solid 1px red;
        margin: 20px auto;
        position: relative;
        cursor: pointer;
    }
    .detail{
        width: 400px;
        height: 200px;
        box-sizing: border-box;
        border: solid 1px red;
        position: absolute;
        top: 38px;
        right: -1px;
        display: none;
        z-index: -1;
    }
    
</style>
<body>
    <div class="box" id="shopbtn">
        <span>Shopping Cart</span>
        <div class="detail" id="content" style="display: none;">//Since the binding event modification style is to add an introverted style, we must actively add none first to judge whether it is currently none or block when obtaining it later
            Hidden content
        </div>
    </div>
    <=script>
        let box = document.getElementById("shopbtn");//Get the target clicked by the external box
        let detail =document.getElementById("content");//Assign the display target to the variable detail
        box.onclick = function(){
            let n = detail.style.display;//Get the style value of detail and assign it to the variable n
            if(n==="none"){     //Determine whether the current value of n is none or block
                detail.style.display="block";
                box.style.borderBottomColor = "white";
            }else{
                detail.style.display="none";
                box.style.borderBottomColor = "red";
            }
            
        }
    </=script>
</body>
</html>

loop

Repeat something

  • for loop
    • 1. Create initial cycle value
    • 2. Set (verify) the conditions for loop execution
    • 3. If the condition is true, execute the operation in the loop body
    • 4. Execute step accumulation at the end of the current cycle
    • 5. When the loop is nested, the outer loop executes once and the inner loop executes all
      ex1:
for (int i = 0; i < 4; i++ )
  {
    System.out.println("i==>"+i);
    for (int j = 0; j < 3; j++ )
    {
      if( j==1){
        continue;
      }
      System.out.println(j);
    }
  }

//The output result is:
i==>0
0
2
i==>1
0
2
i==>2
0
2
i==>3
0
2

ex2:

for (var i=10;i>4;i-=2){
  if(i<7){
    i++;
  }else{
    i--;
  }
}
console.log(i);
//The first time: i=10, judge i > 4?, Results it is established to execute the loop operation, i=10, judge i < 7?, If i --, i=9, i-=2,i=7 will be executed finally;
//The second time: i=7, judge i > 4?, Results it is established to execute the loop operation, i=7, judge i < 7?, If i --, i=6, i-=2,i=4 will be executed finally;
//The third time: i=4, judge I > 4?, The result is not tenable, exit the cycle, and the final output result is i=4

Two keywords in the loop:

  • Continue: end the current cycle (the code after continue is no longer executed) and continue to execute the next cycle
    -Break: force the end of the whole loop (the code behind the break is no longer executed), and the whole loop ends without doing anything
    ex3:
//question: how many i are output in total? What are they?
for(var i=0;i<10;i++){
  if(i>=2){
    i+=2;
    continue;
  }
  if(i>=6){
    i--;
    break;
  }
  i++;
  console.log(i);
}
console.log(i);
//i=0, judge i < 10?, Establishment judgment i > = 2?, If not, judge i > = 6?, If it does not hold, execute i + +, output i is 1, and finally the loop increases to 2
//i=2, judge I < 10?, Establishment judgment I > = 2?, If yes, execute i+=2,i=4, and the code after continue will not be executed. The cycle will increase by 1,i=5
//i=5, judge I < 10?, Establishment judgment I > = 2?, If yes, execute i+=2,i=7, and the code after continue will not be executed. The cycle will increase by 1,i=8
//i=8, judge I < 10?, Establishment judgment I > = 2?, If yes, execute i+=2,i=10, and the code after continue will not be executed. The cycle will increase by 1,i=11
//i=11, judge I < 10?, If not, the loop ends, the last output statement is executed, and the output is i=11;
//A total of two i are output, the first i=1 and the second i=11
  • for in loop
  • for of loop
  • while Loop
  • do while loop

Stack memory pointing problem

box.style.color="red";
//Can you modify the element style in the following ways
//The first way
let a = box.style;
a.color="red";//sure
//The second way
let b = box.style.color;
b = "red";//may not

  • docment. The element obtained by getelementbyid is the value of the object data type
    //We can use console Log (typeof box) detected object type
  • be based on. dir can see the details of an object, which is essentially an object, including the attribute name and attribute value of the object
    • ID: the ID value of the operation element
    • className: class style value of operation element
    • innerHTML: operate the content of the element (can identify the tag)
    • InnerText: the difference between innerText and innerHTML is that tags are not recognized
    • Style: the inline style of the action element
    • tagName: get the tag name of the element (generally uppercase)
      ...
      //We can use console Dir (box) to view all attributes of an element

Parity line discoloration

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Parity line discoloration</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        ul{
            list-style: none;
        }
        #liBox{
            box-sizing: border-box;
            width: 400px;
            height: 400px;
            border: solid 1px gold;
            margin: 0 auto;
        }
        #liBox>li{
            line-height: 80px;
            text-align: center;
        }
        /* #liBox>li:nth-of-type(even){
            background-color:red;
        } */
    </style>
</head>
<body>
    <ul id="liBox">
        <li>I'm the first li</li>
        <li>I'm the second li</li>
        <li>I'm the third li</li>
        <li>I'm the fourth li</li>
        <li>I'm the fifth li</li>
    </ul>
    <=script>
        // let liBox=document.getElementById("liBox");
        let newsList=liBox.getElementsByTagName("li");
        //1. Realize parity line discoloration
        //Loop to get each li, judge each li parity line, and make it have different colors
        for(let i=0;i<newsList.length;i++){
            //The first round i=0, operate the first Li,newsList[0]
            //The second round i=0, operate the second Li,newsList[1]
            //...
            //Get current list
            let curLi= newsList[i]
            if(i%2==0){
                //If i modulus is 0, i is an even number, but if the array starts from 0, it is an odd line
                curLi.style.background="red";//Odd behavior red
            }else{
                curLi.style.background="green";//Even behavior green
            }
        //2. Cycle to add mouseover/mouseout events to each LI
            curLi.onmouseover=function(){
                //When moving in, the background color changes to white
                curLi.style.background="white";//Move in to white
            }
            curLi.onmouseout=function(){
                curLi.style.background="gold";//Change to gold
                //How to determine the original background color when moving out?
            }
        }

    </=script>
</body>
</html>

function

A function is a method or a function body. A function actually encapsulates the code that implements a function. In the future, if you want to operate and implement the function, you only need to execute the function = > "encapsulation", which reduces the redundancy of the code and improves the reuse rate of the code, that is, high cohesion and low coupling

The washing machine is a function. The production of the washing machine encapsulates a function. During production, we don't know what water, clothes, washing liquid, etc. the user will put when washing clothes. We need to provide access (the access provided is called a formal parameter in the function, and the specific things put in during execution are called arguments). After washing clothes, we need to take them out, The washing machine provides an exit (called return value in the function: the result processed by the function can be returned to the outside for use)

  • Create function
    • Formal parameter
    • Return value
  • Execution function
    • Argument
  • arguments
  • Function underlying operation mechanism
  • ...

Create function

//es5 old way
function [Function name]([Parameter variable 1],[Formal parameter variable 2]...){
  //Function body: functions implemented based on JS;
  return [Results after treatment];
}

//Execution function
[Function name]([Argument 1]...);

ex:

//Define a function, find the sum of two numbers, then multiply the value by 10 and divide by 2 to return the result to the output
function sum(n,m){
  //Initialization parameters
  if(n === undefined){
    n = 0;
  }
  if(typeof m === "undefined"){
    m = 0;
  }//Like the above initialization method, this method is generally used
  let res = n+m;
  res *= 10;
  res /= 2;
  console.log(res)
}
sum(1,2);//Call the function, passing two arguments 1 and 2

Function return value problem

If the return value of the function is not set, the external calling function will default to undefined
Return value return must return a value
Return encountered in the function body may not have a return value, or the following code may not be executed

<=script>
        function sum(m,n){
            //initialize variable
            if(typeof m==="undefined"){
                m=0;
            }
            if(typeof n === "undefined"){
                n=0;
            }
            let res = m+n;
            return res;//Return must return a value. If there is no return value, the result of the call outside the function is undefined
        }
        //console.log(res);=>Uncaught ReferenceError: res is not defined
        let a=sum(10,20);//If you want to call the return value of this function, you need to define a variable to accept the return value
        console.log(a);
    </=script>

Anonymous function

Expression of anonymous function: assign an anonymous function itself to other things. Generally, this function is not triggered and executed manually, but triggered and executed by other programs
ex:

document.body.onclick=function(){}
setTimeout(function(){},1000)//Set a timer and execute the anonymous function after 1000ms

Self executing function of anonymous function: after an anonymous function is created, it is immediately executed by adding a parenthesis
ex:

(function(n){})(100)//The value of n in the function is 100

Tab exercise

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>tab </title>
</head>
<style>
    *{
        margin: 0;
        padding: 0;
    }
    #selBox{
        box-sizing: border-box;
        width: 400px;
        margin: 20px auto;
        /* border: solid 1px red; */
        
    }
    #selNav{
        display: flex;
        list-style: none;
    }
    #selNav>li{
        height: 35px;
        line-height: 35px;
        box-sizing: border-box;
        border: solid 1px green;
        padding: 0 10px;
        margin-right: 10px;
        cursor: pointer;
    }
    #selNav>li.active{
        border-bottom-color: white;
    }
    #selBox>div{
        height: 150px;
        box-sizing: border-box;
        border: solid 1px green;
        position: relative;
        top: -1px;
        display: none;
        z-index: -1;
    }
    #selBox>div.active{
        display: block;
    }
</style>
<body>
    <div id="selBox">
        <ul id="selNav">
            <li class="active">read</li>
            <li>programming</li>
            <li>motion</li>
        </ul>
        <div class="active">Reading makes me happy</div>
        <div>Programming makes me sick</div>
        <div>Exercise keeps me healthy</div>
    </div>
    <=script>
        //Get DIV with ID selBox
        var selBox=document.getElementById("selBox");
        //Get the three divs under the DIV with ID selBox and assign them to selBoxList
        var selBoxList=selBox.getElementsByTagName("div");
        //Get UL with ID selNav
        var selNav=document.getElementById("selNav");
        //Obtain the three LI under the UL with ID selNav and assign them to selNavList
        var selNavList=selNav.getElementsByTagName("li");


        //Loop through three LI and bind click events to each LI
        //selNavList[i] is the li that we need to operate under the current loop. For example, selNavList[0] is the first li, with reading content
        //============The following methods cannot be implemented===============================
        // for(var i=0;i<selNavList.length;i++){
        //     selNavList[i].onclick=function(){
        //         console.log(i);// All I output is 3, because the web page is displayed to the user to run the whole code. Since we added a click event to selNavList[i], the user can click only after the web page is loaded, and this click event will not be triggered when loading i=0,i<3,selNavList[0],selNavList[0]. Onclick = function() code will not be executed. I + + is followed by 1. Repeat the loop. When i=3, exit the loop Then run the complete code and display it to the user, and then the user clicks the trigger function, but i=3 at this time, so changeTab(3) will not be found.
        //         changeTab(i);
        //     }
        // }


        //===============Solution 1 Set custom properties==============================
        for(var i=0;i<selNavList.length;i++){
            selNavList[i].myindex=i;//Set a custom attribute myindex for each LI. The attribute value stores the index of the current LI
            selNavList[i].onclick=function(){
                changeTab(this.myindex);//this.myindex gets the index value previously bound to the custom attribute
            }
        }

        //Cycle process
        //i=0  selNavList[0].myindex=0
        //selNavList[0].onclick=function(){...}
        //i=1  selNavList[1].myindex=1
        //selNavList[1].onclick=function(){...}
        //...



        //===============Other solutions 1==============================
        //Method Closure 
        for(var i=0;i<selNavList.length;i++){
            selNavList[i].onclick=(function (i){
                return function(){
                    changeTab(i);
                }
            })(i);
        }



        //===============Other solutions 2==============================
        //let solution in es6
        for(let i=0;i<selNavList.length;i++){
            selNavList[i].onclick=function(){
                changeTab(i);
            }
        }



        
        //Encapsulation function to switch tabs
        //You don't know who you clicked when creating the function, so define an entry clickindex (to store the index of the clicked item), and pass the index of the clicked item when executing the method
        function changeTab(clickindex){
            //1. Remove all LI and DIV styles first
            for(var i=0;i<selNavList.length;i++){
                selNavList[i].className="";
                selBoxList[i].className="";//Since the number of DIV and LI is the same, there are three, so they can be written together
            }
            //2. Click who adds active style to who
            selNavList[clickindex].className="active";
            selBoxList[clickindex].className="active";
        }
    </=script>
</body>
</html>

Common output methods

  • console.log
  • console.dir

dir outputs the detailed key value pair information of an object

  • console.table

A multi-dimensional json array is output in a tabular manner on the console

  • Multidimensional array
    • [10,12] one dimensional array
    • [10,{name: "xxx"}] two dimensional array
    • [12,[{xxx: "xxx"}]] 3D array

Browser window pop up

  • Alert (pop-up box)
  • Confirm (confirm selection pop-up box)
  • Prompt (one more input box based on confirm)

The three result output methods must first be converted to strings through toString
All three methods will block the execution of the current JS code

js is placed at the end of head and body

Put it in the header. If the code in JS needs to obtain elements to operate on elements, it will not be obtained. If it must be placed in the header, you can use window ο nl ο ad=function() {}, but the window method can only be used once. There is a similar method $(document) in JQ ready(function(){})

<head>
<=script>
window.onload=function(){
  JS code
}
</=script>
</head>

Further understanding of objects

var name=10;
var obj ={
name: "Xiao Wang"
};
console.log(obj.name);// Output Xiao Wang
console.log(obj[“name”]);// Output Xiao Wang
console.log(obj[name]);// Equivalent to obj [10] = > output undefined

var name = "Xiao Wang"
var obj={
name:name,
Name, / / simplified in ES6, equivalent to name:name
}

for in to traverse the property names in the object

var obj={
name: "Xiao Wang",
age:"18",
1:10,
2:20,
3:30
}
for(var key in obj){
console.log("attribute name:" + key + "attribute value:" + obj[key])
}Key is used to output all attribute names in the current obj, starting with the smallest number of attribute names, and obj[key] is used to output all attribute values

Deep understanding of custom attributes

In the early stage, some values are stored on the user-defined attributes. When needed in the later stage, these values can be obtained directly from the attributes

Interlaced discoloration, discoloration when sliding, and can maintain the original color

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Interlaced discoloration,And leave to restore the original color</title>
</head>
<style>
    *{
        margin: 0;
        padding: 0;
    }
    #box{
        list-style: none;
        width: 400px;
        margin: 20px auto;
    }
    #box li{
        height: 40px;
        line-height: 40px;
        box-sizing: border-box;
        border-bottom: dashed 2px #999;
    }
</style>
<body>
    <ul id="box">
        <li>This is the first one li</li>
        <li>This is the second li</li>
        <li>This is the third li</li>
        <li>This is the fourth li</li>
        <li>This is the fifth li</li>
    </ul>

    <=script>
        let box = document.getElementById("box");
        let liList=box.getElementsByTagName("li");
        //Loop through each li
        for(var i=0;i<liList.length;i++){
            //Judge by taking the remainder of the value of i. odd numbers are even lines, which are green, and even numbers are odd lines, which are white
            let bg=i%2===0?"white":"green";
            liList[i].style.backgroundColor=bg;
            //Customize an attribute to store the previously obtained color value
            liList[i].myOriginBg=bg;
            //Loop to add a mouse over event to each li
            liList[i].onmouseover=function(){
                this.style.backgroundColor="blue";
            }
            //Loop to add a mouse out event to each li
            liList[i].onmouseout=function(){
                this.style.backgroundColor=this.myOriginBg;
            }
        }
    </=script>
</body>
</html>

arguments

1. Class array collection, which stores the actual parameter information passed during the execution of all functions
2. arguments exist whether formal parameters are set or not
3. arguments exist regardless of whether the argument is set or not

Summation of arbitrary numbers

1. The number of arguments passed is uncertain
2. Whether the value passed is a significant number is uncertain
3. It is necessary to sum the transmitted significant numbers and output the results

**ex:**

<script>
        function anyNumSum(){
            let total = null;//Define a variable to receive the summation value, which is null by default
            //The circular class array arguments has as many key value pairs as there are arguments
            for(var i=0;i<arguments.length;i++){
                var list=Number(arguments[i]);//Converts the value obtained by the loop to numeric
                if(isN Determine whether there are non significant figures
                    continue;
                }
                total+=list;//Accumulated acquired values
            }
            return total;
        }
        let a=anyNumSum(10,20,'1');
        console.log(a);//The result is 31
    </script>

Initial knowledge of arrow function (existing in Es6 syntax specification)

<script>
  //Function creation in old syntax specification
  function sum(n,m){
    return n+m;
  }
  //Overridden arrow function
  let sum = (n,m) => {
    return n+m;
  }

  //If there is only one line return in the arrow function, return and curly braces can be omitted
  let sum =(n,m) => n+m;


  //fn nesting in old grammar
  function fn(n){
    return function(m){
      return n+m;
    }
  }

  //Rewrite to arrow function
  let fn = (n) => (m) => n+m;

  //In the old syntax, the formal parameter assigned to unassigned value is set to 0
  function sum(m,n){
    if(typeof m==="undefined"){
      m=0;
    }
    if(typeof n==="undefined"){
      n=0;
    }

    return m+n;
  }

  //Change to arrow function
  let sum=(m=0,n=0)=>m+n;//In traditional function, it can also be written directly in m and n, but it is generally not written in this way
</script>

``**be careful:**``Not in arrow function arguments,But it can be used...Variable name(Remaining operators to get the set of arguments passed),It and arguments The difference is that it is an array,and arguments Is an array of classes,Then you can use the array processing method for subsequent operations

<script>
  let sum=(...arg)=>{
    return eval(arg.join('+'));//arg.join('+') is to splice the Arg array into a string, and eval is the calculated result
  }
  sum(1,2,3,4)//The result returns 10
</script>

reflection:
let sum=(...arg)=>{
return eval(arg.join('+'));
}
sum(1,2,3,4)//10
Math.max(sum(1,2,3))//6
Math.max(sum([1,2,3]))//3
sum([1,2,3])//3
sum(1,2,3)//6
sum([1])//1
sum([1,2])//2

Math function math in JS

Math math function: it is not a function itself, but an object. Many attribute methods for operating math are stored in the object, so it is called math function

Attributes and methods commonly used in Math

Math.abs([number value]) takes the absolute value of a number. If it is not a number, it will be converted into a number based on the Number() method
Math.ceil/floor([number value]) rounds up (the rounding must be larger than the original number) / down (the rounding must be smaller than the original number). If it is not a number, it will be converted into a number based on the Number() method
Math.round([number value]) rounding method (if it is a negative number, it will be rounded off). If it is not a number, it will be converted into a number based on the Number() method
Math.max/min([val1],[val2]...) obtains the maximum / minimum value in a stack

**Thinking question: * * find math max/min([10,20,30,40,50])

Math.sqrt([number value]) gives the square of a number (negative numbers cannot be square)
Math.pow([val],[val]) calculates the power of a number
Math.random() gets a random decimal between 0 and 1

  • Math.round(Math.random()) / / get 0 or 1 randomly
  • Math.round(Math.random()*(m-n)+n) / / randomly output n-m integers

array

    let ary=[12,23,34,45];
    console.log(typeof ary);=>object
    console.dir(ary);
      ary={
        0:12,
        1:23,
        2:34,
        3:45,
        length:4
      }
      Number as index
      length Represents the length of the array
      ary[0] Gets the content of the specified item according to the index
      ary.length Get array length
      ary.length-1 Gets the index of the last item

Common methods in arrays

  • Learn array operations as follows
    • Function and meaning of method
    • Method arguments (type and meaning)
    • Method
    • Will the original array change

1. Methods for adding, deleting and modifying arrays (this part of methods will modify the original array)

  • push: adds content to the end of the array
    • @params
      Multiple arbitrary types
    • return
      Length of array after adding
    let ary =[10,20];
    let res=ary.push(30,'AA',{name:'Xiao Wang'}); => Add content to the end of the array
    ary[ary.length]=40; => Based on native JS Add content to the last item in the array
    console.log(ary,res); => Array length changed from 2 to 5,res=5 ary=[10,20,30,'AA',{name:'Xiao Wang'}]
  • unshift: adds content to the beginning of the array
    • @params
      Multiple arbitrary types
    • return
      Length of array after adding
    let ary =[10,20];
    let res=ary.unshift(30,'AA',{name:'Xiao Wang'}); => Add content to the beginning of the array
    ary=[50...ary]; => Based on native ES6 Expand operator,Clone the original array,Create the first item in the new array,The remaining contents use the original array contents,Adding to the beginning is also realized
    console.log(ary,res); => Array length changed from 2 to 5,res=5 ary=[30,'AA',{name:'Xiao Wang'},10,20,]
  • shift: deletes the first item in the array
    • @params
      No,
    • return
      The item deleted
    let ary =[10,20,30,40];
    let res=ary.shift(); => Delete the beginning of the array
    delete ary[0]; => Based on native JS Medium delete,Treat arrays as normal objects,Are you sure you can delete an item,However, it will not affect the structural characteristics of the array itself(length The length will not change),This method cannot be used to delete in real projects
    console.log(ary,res); => res=10 ary=[20,30,40]
  • pop: delete the last item in the array
    • @params
      No,
    • return
      The item deleted
    let ary =[10,20,30,40];
    let res=ary.pop(); => Delete the last item in the array
    ary.length--; => Based on native JS,Let the array delete one bit(The last bit is deleted by default)
    console.log(ary,res); => res=40 ary=[10,20,30]
  • splice: implement the addition, deletion and modification of arrays
    • Delete part
    • @params
      n. m is all numbers. m elements are deleted from index n (m is deleted until the last if m is not written)
    • return
      The deleted part is stored and returned with a new array
    let ary =[10,20,30,40,50,60,70,80,90];
    let res=ary.splice(2,4); => Delete array index, starting from 2,Delete four items(If there is only one number,Then delete it from the beginning to the end)
    console.log(ary,res); => Array length changed from 9 to 5,res=[30,40,50,60] ary=[10,20,70,80,90]
    ary.splice(ary.length-1) => Delete last item
    ary.splice(0,1) => Delete the first item
  • splice: implement the addition, deletion and modification of arrays
    • Added and modified parts
    • @params
      n. m and x are all numbers. m elements are deleted from index n, and x is used to occupy the original deleted position (modified)
      n. 0 and x are all numbers. Starting from index n, do not delete any. Put x in front of index n (add)
    • return
      The deleted part is stored and returned with a new array
    let ary =[10,20,30,40,50,60,70,80,90];
    let res=ary.splice(2,4); => Delete array index, starting from 2,Delete four items(If there is only one number,Then delete it from the beginning to the end)
    console.log(ary,res); => Array length changed from 9 to 5,res=[30,40,50,60] ary=[10,20,70,80,90]

    //Implementation modification
    ary.splice(2,4,'Lao Wang','Lao Li'); => res=[70,80,90] ary=[10,20,'Lao Wang','Lao Li']

    //Implement add
    ary.splice(2,0,'Lao Chen'); => res=[] ary=[10,20,'Lao Chen','Lao Wang','Lao Li']

    //Add to the end of the array
    ary.splice(ary.length,0,'Lao Lei'); => res=[] ary=[10,20,'Lao Chen','Lao Wang','Lao Li','Lao Lei']

    //Add to the beginning of the array
    ary.splice(0,0,'Old cow'); => res=[] ary=['Old cow',10,20,'Lao Chen','Lao Wang','Lao Li','Lao Lei']

Array query and splicing (this group of learning methods will not change the original array)

  • slice: implement array query
    • @params
      n. M is all numbers. Find the item with index m (excluding m) from index n
    • return
      Store and return the found part with a new array
    let ary=[10,20,30,40,50];
    let res=ary.slice(1,3);
    console.log(res,ary) => res=[20,30] ary=[10,20,30,40,50]

    => m Don't write(Find end)
    ary.slice(1) => ary=[20,30,40,50]

    => Array cloning(Shallow cloning,Parameter 0 can be left blank)
    res=ary.slice(0) => res=[10,20,30,40,50]

reflection:
1. What happens if n/m is negative?
2. What happens if n > m?
3. What if it is a decimal?
4. What if it is a non significant figure?
5. What if the value of m or n is greater than the maximum index?

Answer: 1 I haven't found any rules yet
2. If n > m, it cannot be found
3. Decimal is rounded down
4. If n is a non significant number and m is a significant number, n defaults to 0 If m is not a valid number, it cannot be found
5. If the index of n is larger than the array, it cannot be found. If the index of m is larger than the array, start from the n index to find the complete array

  • concat: realize the splicing of arrays
    • @params
      Multiple values of any type
    • return
      For the new array after splicing, the original array remains unchanged
    let ary1=[10,20,30,40];
    let ar2=[40,50,60,70];
    let res=ary1.concat('Xiao Chen',ary2);
    console.log(res); => res=[10,20,30,40,'Xiao Chen',40,50,60,70];

Convert an array to a string (the original array remains unchanged)

  • toString(): converts an array to a string
    • @params
    • return
      The converted String, each separated by a comma
    let ary=[10,20,30];
    let res=ary.toString();
    console.log(res); => res='10,20,30'
  • join(): converts an array to a string
    • @params
      Specify the delimiter (the delimiter is of string type, and the default comma is not specified)
    • return
      Converted String (original array unchanged)
    let ary=[10,20,30];
    let res=ary.join(); => res="10,20,30"
    res=ary.join(""); => res="102030"
    res=ary.join("|"); => res="10|20|30"
    res=ary.join("+"); => res="10+20+30"
    console.log(eval(res)); => 60 eval Change string to JS Expression

Detects whether the array contains an item

  • indexOf(x,y)/lastIndexOf(x,y): detects the index value of the first / last occurrence position of the current item X in the array
    • @params
      X is the item to be detected (x is not the index value), and y is the index of the starting search location
    • return
      The index value at the position of this item (must be a number). If there is no such item, the result - 1 is returned, and the original array remains unchanged;
    let ary=[1,2,3,1,2,3];
    console.log(ary.indexOf(2)); => 1
    console.log(ary.lastIndexOf(3)); => 5

    Detect whether the array contains"Xiao Chen"
    if(ary.indexOf("Xiao Chen")===-1){
        Not included
    }else{
        contain
    }
  • includes(): detects whether the current item has appeared in the array
    • @params
      This item to be detected
    • return
      true is returned in case of occurrence, and false is returned in case of no occurrence
let ary=[1,2,3];
let res=ary.includes(4); => res=false

Sorting or arrangement of arrays (the original array is changed)

  • reverse(): reverse the array
    • @params
    • return
      The new array after arrangement changes the original array
let ary=[1,2,3];
let res=ary.reverse(); => res=[3,2,1] ary=[3,2,1]
  • sort(): sort arrays (from small to large)
    • @params
      Optional or a function (* * Note: * * if parameters are not passed, only those below 10 can be sorted (excluding 10), which is sorted according to the first character of each item by default)
    • return
      The new array after arrangement changes the original array
    let ary=[7,8,5,2,4,6]
    let res=ary.sort(); => res=[2,4,5,6,7,8]
    let ary1=[12,15,9,28,10,22];
    res=ary1.sort(); => res=[10,12,15,22,28,9]

    => If you want to achieve descending or ascending order, you need to sort Internal write function
    let res=ary1.sort(function(a,b){
      return a-b; => Implement ascending order res=[9,10,12,15,22,28]
      return b-a; => Implement descending order res=[28,22,15,12,10,9]
    });

    => Rewrite to arrow function
    let res=ary1.sort((a,b)=>a-b); res=[9,10,12,15,22,28];
    let res=ary1.sort((a,b)=>b-a); res=[28,22,15,12,10,9];

Method of traversing the array (the original array will not be changed)

  • forEach()

  • map()

  • filter()

  • find()

  • reduce()

  • some()

  • every()

  • ...

  • forEach(): traverses each item in the array

    • @params
      Callback function
    • return
      If there is no return value, the original array will not be changed
  => be based on for Loop to solve the problem of array traversal
    let ary=['I','yes','old','king','ah'];
    for(let i=0;i<ary.length;i++){
    console.log('Indexes:'+i+' '+'The content is:'+ary[i]);
  }

  =>use forEach()
  let ary=['I','yes','old','king','ah'];
  ary.forEach((item,index)=>{
    console.log('Indexes:'+index+'The content is:'+item);  =>The first parameter in the arrow function is the index content(Whatever the name),The second is the index(Whatever the name)
  });

Array de duplication

=>Method 1:
1. Create a new array and traverse each item of the original array
2. If there is no such item in the new array, add it to the new array

    let ary=[1,3,2,4,2,3,3,4,1,2,2,1,3,4,4];
    let newAry=[];
    for(let i=0;i<ary.length;i++){
      let item=ary[i]; => Loop each item in the original array to item
      if(newAry.includes(item)){
        continue; => If the new array contains this item, the current loop is skipped;
      }
      newAry.push(item);
    }
    console.log(newAry);


Optimization method I(IE6,7,8 incompatible):
    let newAry=[];
    ary.forEach((item)=>{
      if(newAry.includes(item)) return;
      newAry.push(item);
    });
    newAry.sort((a,b)=>{
      return a-b;
    });
    console.log(newAry);

=>Scheme 2 (how to solve array collapse when operating in the original array):
1. First take out each item A of the array
2. Compare this item A with each subsequent item in turn. If it is the same as the current item A, delete this item from the original array

        let ary=[1,3,2,4,2,3,3,4,1,2,2,1,3,4,4];
        for(let i=0;i<ary.length;i++){
            let item=ary[i];
            =>i=0 item=1 j=1 compare=3 1!==3
            =>i=0 item=1 j=2 compare=2 1!==2
            =>i=0 item=1 j=3 compare=4 1!==4
            =>i=0 item=1 j=4 compare=2 1!==2
            =>i=0 item=1 j=5 compare=2 1!==3
            =>i=0 item=1 j=6 compare=2 1!==3
            =>i=0 item=1 j=7 compare=2 1!==4
            =>i=0 item=1 j=8 compare=2 1===1 ary.splice(8,1) ary=[1,3,2,4,2,3,3,4,(1),2,2,1,3,4,4] j-- =>j=7 j++ =>j=8
            =>i=0 item=1 j=8 compare=2 1!==2
            =>...
            for(let j=i+1;i<ary.length;j++){
            let compare=ary[j];
                if(item === compare){
                ary.splice(j,1);
                j--; => Because every time you delete,The index of the following element moves forward one bit,Therefore, in order to ensure that the subsequent operations remain unchanged,The index will be reduced and then increased
                
            }
        }
    }
        ary.sort((a,b)=>{
        return a-b;
        });
        console.log(ary);

=>Scheme 3 (create an object. If the array contains objects, this method cannot be used):

    let ary=[1,3,2,4,2,3,3,4,1,2,2,1,3,4,4];
    let obj={};
    => Loop through each item in the array,Store each item in the array(item:item)(The contents of the array as objects obj Property name and property value)
    for(let i=0;i<ary.length;i++){
      => i=0 ary[0]=1 item=1 obj[1]==undefined obj[1]=1;
      => i=1 ary[1]=3 item=3 obj[3]==undefined obj[3]=3;
      => i=2 ary[2]=2 item=2 obj[2]==undefined obj[2]=2;
      => i=3 ary[3]=4 item=4 obj[4]==undefined obj[4]=4;
      => i=4 ary[4]=2 item=2 obj[2]!==undefined splice(4,1) ary=[1,3,2,4,(2),3,3,4,1,2,2,1,3,4,4] i-- =>i=3 i++=>i=4;
      => i=4 ary[4]=3 item=3 obj[3]!==undefined splice(4,1) ary=[1,3,2,4,(3),3,4,1,2,2,1,3,4,4] i-- =>i=3 i++=>i=4;
      => i=4 ...
      let item=ary[i];
      if(obj[item]!==undefined){
        =>Judge before each storage,If obj This item exists in,It needs to be deleted
        ary.splice(i,1);
        i--;=>Solve array collapse problem
        continue;
      }
      obj[item]=item;
}

=>Scheme III (optimizing performance)

    let ary=[1,3,2,4,2,3,3,4,1,2,2,1,3,4,4];
    let obj={};
    => Loop through each item in the array,Store each item in the array(item:item)
    for(let i=0;i<ary.length;i++){
      let item=ary[i];
      //Judge before each storage. If this item exists in obj, it needs to be deleted
      if(obj[item]!==undefined){
        ary[i]=ary[ary.length-1]; => Swap the item to be deleted with the last one,Then delete the last item
        ary.length--;
        i--;
        continue;
      }
      obj[item]=item;

=>Write as function

/*
 *  unique: Implementation of array de duplication method
 *  @params
 *    ary [Array] Array to be de duplicated
 *  @return
 *    De duplicated array
 *  by cly on 2021.5.3
 */

    function unique(ary){
      let obj={};
      for(let i=0;i<ary.length;i++){
        let item=ary[i];
        if(obj[item]!==undefined){
          ary[i]=ary[ary.length-1];
          ary.length--;
          i--;
          continue;
        }
        obj[item]=item;
      }
      return ary;
    }

=>Method 4 (Set de duplication, based on ES6, this method can realize fast de duplication)

    let let ary=[1,3,2,4,2,3,3,4,1,2,2,1,3,4,4];
    ary=[...new Set(ary)];
    console.log(ary);

Common methods in string

All enclosed in single quotation marks, double quotation marks and back quotation marks are strings

    let str='xiaochen'
    str.length => String length
    str[0] => Gets the with index 0(first)character
    str[str.length-1] => Gets the last character str.length-1 Last index

    => Loop through each character in the output string
    let str="xiaowang"
    for(let i=0;i<str.length;i++){
      let char =str[i];
      console.log(char);
}
  • charAt(): gets the character at the specified position according to the index

    • @params
      n [number] gets the index specified by the character
    • return
      Returns the character found
      Not found. An empty string was returned instead of undefined
  • charCodeAt(): gets the ASCII code value (Unicode code value) of the specified character

    • @params
      n [number] gets the index specified by the character
    • return
      Return coded value
    let str='xiaoxiao'
    console.log(str.charAt(0)); => 'x'
    console.log(str[0]); => 'x'
    console.log(str.charAt(10000)); => ''
    console.log(str[10000]); => undefined
    console.log(str.charCodeAt(0)); => 120;
    console.log(String.fromCharCode(121)); => 'y'
  • substr(n,m): interception of string (find what you want in the original string)

    • @params
      n is the index value of the string. m strings are intercepted from the string index of n. if m is not written, it is intercepted to the end (similar to splice)
    • return
  • substring(n,m): interception of string

    • @params
      n. M is the index value of the string, intercepted from the string index of n to the index of M (excluding m, similar to slice in the array)
    • return
  • slice(n,m): interception of string

    • @params
      n. M is the index value of the string. It is intercepted from the string index of n to the index of M (excluding m), but slice can support negative numbers as indexes. Neither of the first two methods can work (negative indexes can be found by str.length + negative index)
    • return
    let str='xiaoxiao'
    console.log(str.substr(2,3)); => 'aox'
    console.log(str.substring(2,3)); => 'a'
    console.log(str.slice(-4,-1)); => 'xia' str.length=8 str.slice(8-4,8-1);
  • indexOf(x,y)/lastIndexOf(x,y): get the index of the first / last occurrence position of the X character in the string
    • @params
      x is the character to be searched, and y is the index of the starting search position
    • return
      Returns the index of the location found, or - 1 if not found
    let str='xiaoxiaonihaowoshixiaochen';
    console.log(str.indexOf('a')); => 2
    console.log(str.lastIndexOf('o'); => 21
    console.log(str.includes('@')); => false
    console.log(str.indexOf('@')); => -1
    console.log(str.indexOf('ni')); =>8
    console.log(str.indexOf('niho')); => -1
    console.log(str.indexOf('x',5)); => 18 Find the first occurrence of the character after index 5'x'Index of
  • toUpperCase()/toLowerCase(): letter to uppercase / lowercase
    • @params
    • return
      Upper / lower case result after conversion
    let str='xiaoxiao'
    console.log(str.toUpperCase()); => XIAOXIAO
    console.log(str.toLowerCase()); => xiaoxiao

    => Capitalize the first letter,The remaining letters are lowercase
    str=str.substr(0,1).toUpperCase()+str.substr(1); => Xiaoxiao
  • split([separator]): splits the string into an array according to the specified separator (corresponding to the join in the array)
    • @params
    • return
      Converted results
    => Change the vertical bar separator to a comma separator
    let str='music|movie|eat|sport';
    let ary=str.split("|"); => ["music", "movie", "eat", "sport"]
    str=ary.join(","); => "music,movie,eat,sport"
    console.log(str);
  • Replace (old character, new character): realize the replacement of string (often used with regular)
    • @params
    • return
      Converted results
let str='Xiao Chen@Xiao Wang@Xiao Lei';
str=str.replace('@','-'); => "Xiao Chen-Xiao Wang@Xiao Lei" Without using regular expressions,Execute once replace Characters can only be replaced once
str=str.replace(/@/g,'-'); => "Xiao Chen-Xiao Wang-Xiao Lei" /@/g,Is a regular expression,g Represent the overall situation

Implement some common requirements

Processing of time string

let time='2021-5-14 11:43:20'
=> Change to the format you need,for example:
'2021 May 25, 2014 11:43:20'

Scheme I,always replace
time = time.replace('-','year').replace('-','month').replace(' ','day ').replace(':','Time').replace(':','branch')+'second';
console.log(time);

Scheme II,Method to get value
let n=time.indexOf('-'); =>Get string'-'First occurrence index,Assign it to a variable n
let m=time.lastIndexOf('-'); =>Get string'-'Last occurrence index,Assign it to a variable m
let x=time.indexOf(' '); =>Get string' 'First occurrence index,Assign it to a variable x
let y=time.indexOf(':'); =>Get string':'First occurrence index,Assign it to a variable y
let z=time.lastIndexOf(':'); =>Get string':'Last occurrence index,Assign it to a variable z
let year=time.substring(0,n); =>Start at index 0,Intercepted index is n Item(Not included n),Get to year
let month=time.substring(n+1,m); =>From index n Start with the last item,Intercepted index is m Item(Not included m),Get to month
let day=time.substring(m+1,x); =>From index m Start with the last item,Intercepted index is x Item(Not included x),Get to date


adopt split Splitting of items
let n=time.split(' '); =>By string' ',Split the whole time into two arrays["2021-5-14", "11:43:20"]
let m=n[0].split('-'); =>By string'-',Split the first content of the array into an array["2021", "5", "14"]
let x=n[1].split(':'); =>By string':',Split the second content of the array into an array["11", "43", "20"]

Direct full split through regular expressions
let ary=time.split(/(?: |-|:)/g); =>ary=["2021", "5", "14", "11", "43", "20"]
time=addZero(ary[0])+'year'+addZero(ary[1])+'month'+addZero(ary[2])+'day'+' '+addZero(ary[3])+'Time'+addZero(ary[4])+'branch'+addZero(ary[5])+'second'

=>If the time is less than two digits,You need to fill in a 0 before it
function addZero(val){
  if(val.length<2){
    val='0'+val;
  }
  return val;
}

Implement a method jueryurlparameter (get the parameter information passed after the question mark of a URL address)

Get an object that contains{
lx:'1',
name:'xiaoyu',
age:'18',
HASH:'box1'
}

let url1='https://sports.qq.com/kbsweb/game.htm?lx=1&name=xiaoyu&age=18#box1';
let url2='https://sports.qq.com/kbsweb/game.htm?mid=100000:55077655#box2';
let result={};

let askIndex=url1.indexOf('?'); =>Get?First occurrence index
let wellIndex=url.indexOf('#'); =>Get#First occurrence index
let askText=url1.subString(askIndex+1,wellIndex); =>Get?reach#Content between (excluding both ends), LX = 1 & name = Xiaoyu & age = 18
let wellText=url1.subString(wellIndex+1) =>Get#The following contents (excluding both ends), box1

let askAry=askText.split('&'); =>["lx=1", "name=xiaoyu", "age=18"]
askAry.forEach((item)=>{
  let n=item.split('=');
  //console.log(n) ["lx", "1"]["name", "xiaoyu"]["age", "18"]
  let key=n[0];
  let value=n[1];
  //console.log(key,value); lx 1 name xiaoyu age 18
  result[key]=value;
});
result['HASH']=wellText;

Encapsulate queryURLparameter into a method

function queryURLParams(url){
  let askIndex=url.indexOf('?'),
      wellIndex=url.indexOf('#'),
      askText='',
      wellText='',
      result={};
  if(wellIndex===-1){
    wellIndex=url.length; =>No,#Then let the index be the length of the entire url
  }else{
    wellText=url.substring(wellIndex+1); =>take#The content behind the index is intercepted to wellText
    result['HASH']=wellText;
  }
  if(askIndex!==-1){
    askText=url.substring(askIndex+1,wellIndex); =>Intercept from index?The latter item starts,To index#(not included)
    let askAry=askText.split('&'); =>Will from?reach#The intercepted contents are divided into array contents by &
    askAry.forEach((item)=>{
    let n=item.split('='); =>Will each item Respectively=divide
    result[n[0]]=n[1]; =>n[0]Is the property name divided above n[1]Attribute values divided above
    });
  }
  return result;
}

let paramsObj=queryURLParams(url1); =>{HASH: "box1", lx: "1", name: "xiaoyu", age: "18"}

Simple four digit random verification code (number + letter)

<body>
    <input type="text" id="inpCode">
    <br>
    <span id="ranCode"></span>
    <button style="margin-top: 5px;" id="btn">invisibility,Click me to switch</button>

    <script>
        let inpCode=document.getElementById('inpCode'),
            ranCode=document.getElementById('ranCode'),
            btn=document.getElementById('btn');
    
            function codeChange(){
            let area='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
            let result='';
                for(let i=0;i<4;i++){
                    //One random index per loop
                    let ran=Math.round(Math.random()*61);
                    result += area.charAt(ran);
                }
                ranCode.innerHTML=result;
            }
            codeChange();
            btn.onclick=codeChange;
            inpCode.onblur=function(){
                let val=inpCode.value;
                let code=ranCode.innerHTML;
                if(val.toLowerCase()===code.toLowerCase()){
                    alert("Input successful!");
                }else{
                    alert("Incorrect verification code input,Please re-enter!");
                    inpCode.value='';
                    //Regenerate
                    codeChange();
                }
            }
    </script>
</body>

Basic operation of date object

let time = new Date(); => Obtain the current client (local computer) time, which can be modified by the user and cannot be used as a reference

Some properties and methods are provided in the standard date object for us to manipulate date information

getFullYear() gets the year
getMonth() get month
getDate() get date
getDay() gets the week (0-6 Sunday Saturday)
getHours() get hours
getMinutes() get minutes
getSeconds() get seconds
getMilliseconds() get milliseconds
getTime() gets the millisecond difference between the current date and 1970 / 1 / 1 00:00:00
toLocaleDateString() gets the month, year and day
toLocaleString() gets the complete date, hour, minute and second

Simple small clock case

<head>
    <meta charset="UTF-8">
    <title>Small clock case</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        #clockBox{
            position: absolute;
            right: 0px;
            top: 0px;
            padding: 0px 15px;
            line-height: 40px;
            font-size: 24px;
            background-color: gold;
            background: -webkit-linear-gradient(top left,red,yellow,blue);
            color: white;
        }
    </style>
</head>
<body>
    <div id="clockBox">
    </div>
 /introduce script
        let clockBox=document.getElementById('clockBox');

        //Encapsulates a method in which the number of digits of a date is not two digits supplemented by 0
        function addZero(val){
            val=Number(val);
            return val<10?'0'+val:val;
        }

        //Encapsulates a custom time format method
        function queryTimeDate(){
            let time= new Date(),
            year=time.getFullYear(),
            month=time.getMonth()+1,
            day=time.getDate(),
            week=time.getDay(),
            hour=time.getHours(),
            minute=time.getMinutes(),
            second=time.getSeconds();
            let weekAry=['day','one','two','three','four','five','six'];
            let result=year+'year'+addZero(month)+'month'+addZero(day)+'day'+' '+'week'+weekAry[week]+' '+addZero(hour)+'Time'+addZero(minute)+'branch'+addZero(second)+'second';
            clockBox.innerHTML=result;
        }
        queryTimeDate();//Execute the above functions

        setInterval(queryTimeDate, 1000);//Timer, execute the method once every 1 second
</body>

Continued processing time based on Date object

        let time='2021-5-16 12:0:0'
        //The number of digits is not enough to supplement 0
        function addZero(val){
            val=Number(val);
            return val<10?'0'+val:val;
        }
        //Change time string to standard format
        function handleDate(time){
            time=time.replace(/-/g,'/');
            time=new Date(time);
            let year=time.getFullYear(),
            month=addZero(time.getMonth()+1),
            day=addZero(time.getDate()),
            hour=addZero(time.getHours()),
            minute=addZero(time.getMinutes()),
            second=addZero(time.getSeconds());
            return year+'year'+month+'month'+day+'day'+' '+hour+'Time'+minute+'branch'+second+'second'
        }
        time=handleDate(time);
        console.log(time);

DOM basic operation

document.getElementById() specifies the ID of the element or the element object in the document
[context].getElementsByTagName() gets a set of element collections by tag name in the specified context
[context].getElementsByClassName() gets a set of element collections through the style class name in the specified context (incompatible with IE6-8)
document.getElementsByName() in the whole document, a set of node collections is obtained through the Name attribute value of the tag (only the Name of the form element can be recognized in IE, so we generally only use it for the processing of form elements)
document.head/document.body/document.documentElement gets the head/body / whole page of the page
[context].querySelector([selector]) gets the specified element object through the selector in the specified context (incompatible with IE6-8)
[context].querySelectorAll([selector]) obtains the specified element collection through the selector in the specified context (incompatible with IE6-8)

Element selector:

let box=document.querySelector('#box'); =>  Get object with ID box
let links=box.querySelectorAll('a'); => Get box All under a label

Nodes in JS and attributes describing the relationship between nodes

node (all contents of the page are composed of nodes)
Node collection nodeList (getElementsByName/querySelectorAll obtains all node collections)

Element node (element label)

  • nodeType:1
  • nodeName: uppercase label
  • nodeValue:null

Text node
nodeType:3
nodeName:'#text'
nodeValue: text content
Comment Nodes
nodeType:8
nodeName:'#commen'
nodeValue: comment content
Document node (document)
nodeType:9
nodeName:'#document'
nodeValue:null
...

Attributes that describe the relationship between these nodes (a supplement to DOM operations)

childNodes: get all child nodes = > all children
Children: get the child nodes of all elements (child element label set) = > all element children
Parent: get parent node
firstChild: get the first child node (any node type is possible) = > eldest son
lastChild: get the last child node (any node type is possible) = > youngest son
firstElementChild/lastElementChild: get the first / last element child node (incompatible with IE6-8) big element brother / brother
previousSibling: get the previous brother node (any node type is possible) = > previous brother
nextSibling: get the next brother node (any node type is possible) = > next brother
Previouselementsibling / nexterelementsibling: get brother / brother element node (incompatible with ie6-8) = > brother of previous element / brother of next element
...

<body>
        <ul id="box">
            <li>git and npm operation</li>
            <li>Object oriented and prototyping:Research plug-in source code,Write your own plug-ins</li>
            <li>Closure scope:Stack memory processing</li>
            <li>ES6:From getting started to giving up</li>
            <li>Synchronous asynchronous programming and core:Micro task, macro task, time cycle</li>
            <li>DOM And its event model</li>
            <li>jQuery And source code analysis</li>
            <li>Design pattern:Publish and subscribe, single instance Promise,PromiseA+</li>
            <li>AJAX And cross domain solutions:Encapsulate a super cow X of AJAX library</li>
            <li>One in HTTP Deep as the sea</li>
            <li>Performance security optimization</li>
            <li id="vueBox">VUE Family bucket:vue-cli\vue\vue-router\vuex\vue element...</li>
            <li>vue and vuex Core source code</li>
            <li>Recat Family bucket:create-react-app,antd,antdpro,react,react-dom,react-native,react-router-dom,redux,react-redux,dva,redux-saga,mobx...</li>
            <li>react Core principles</li>
            <li>redux Source code and middleware writing</li>
            <li>webpack</li>
            <li>node and express</li>
            <li>type script</li>
            <li>...</li>
        </ul>

        script>
            let box=document.getElementById('box');
            //Spaces and line breaks are treated as text nodes in standard browsers (not IE6-8)
            console.log(box.childNodes);
            //However, using children in IE6-8 will also treat annotations as element nodes
            console.log(box.children);
            //===================================================
            //Find all node methods that are children of the element
            function queryChildren(context){
                //Get all child nodes
                let res=[],
                nodeList=context.childNodes;
                //Traverse the entire child node. If it is an element node, it will be put into the array
                for(i=0;i<nodeList.length;i++){
                    var item=nodeList[i];//Get the item of the current loop and give it to item
                    item.nodeType===1?res.push(item):null;
                }
                return res;
            }
            console.log(queryChildren(box).length);
            console.log(box.firstChild);
            console.log(box.firstElementChild);
            let vueBox=document.getElementById('vueBox');
            console.log(vueBox.previousSibling); //=>#text because its last brother is a space
            console.log(prev(vueBox.previousSibling)); //=>< li > performance security optimization < / Li > found successfully

            //Find the previous method for the element
            function prev(context){
                //Find the first brother, and then judge whether it is the element brother. If not, find the brother's brother
                var pre=context.previousSibling;
                while(pre.nodeType!==1){
                    pre=pre.previousSibling;
                }
                return pre;
            }
        </script>
</body>

Dynamically add, delete and modify elements in JS

createElement create element object
createTextNode creates a text object
appendChild adds an element to the end of the specified container. Syntax: container appendChild (element)
insertBefore adds an element to the specified container. Syntax: container insertBefore([new element], [specified element])
cloneNode(true/false) clone elements or nodes (deep clone: Clone even child elements / shallow clone: do not clone child elements)
removeChild removes an element from the container

Another way to customize attributes (this way is to put custom attributes on the element structure)

setAttribute sets the custom attribute information of the element
getAttribute gets the custom attribute information of the element
removeAttribute removes the custom attribute information of the element

============Two ways to customize attributes======================
<body>
    <button>This is the first button</button>
    <br>
    <button>This is the second button</button>    
    <br>
    <button>This is the third button</button>
    <br>
    <button>This is the fourth button</button>
    <br>
    <button>This is the fifth button</button>


    <script>
        //var btnList=document.getElementsByTagName("button");
        var btnList=document.querySelectorAll('button');
        for(var i=0;i<btnList.length;i++){
            btnList[i].setAttribute('myindex',i);//Set a custom property
            //btnList[i].myindex=i
            btnList[i].onclick=function(){
                //alert(this.myindex);
                alert(this.getAttribute('myindex'));//Get custom properties
            }
        }
    </script>
</body>

GIT version control system

  • Version controller
    • 1. Record historical version information (record each modification)

The difference between distributed and svn centralized


How git works

  • Workspace: the area we can see and use to write code
  • Staging area: an area for temporary storage
  • History area: generate historical version
  • Central warehouse: the area for collaborative development and storage of the whole code
  • Process: work area - > temporary storage area - > History area - > Central Warehouse (git add-A, git commit -m 'remarks', GIT pull origin master (pull from the warehouse first) git push origin master (submit to the warehouse again))

Global configuration of git

  • After installing git for the first time, we configure the basic information in the global environment (tell git who I am)
  • $git config -l: View configuration information
  • $git config --global -l: view global configuration information
  • Add global for the first time: git config -- global user name ‘xxx’ ,git config --global user.email ‘ xxx@xx.xx ’

Create warehouse to complete version control

  • $git init = > will generate a hidden Git file (cannot be deleted, because it contains some other information of temporary storage area and history area. If deleted, it will not be a complete git warehouse)

After writing the code locally (in the workspace), submit some files to the staging area

  • $git add xxx: submit a file or folder to the temporary storage area
  • $ git add . : Submit all the newly modified files in the current warehouse to the temporary storage area
  • $git add -A: ditto
  • $git status: check the status in the current folder (red indicates that there are files in the work area, green indicates that they are in the temporary storage area, and the invisible content indicates that all modified information files have been submitted to the history area)

Submit the contents of the staging area to the history area

  • $git commit -m 'description information, a description of this submission'

View historical version information

  • $git log: view historical information
  • $git reflog: View rollback information including history

The whole operation flow of git

Connect the local warehouse to the remote warehouse (establish a link between the local warehouse and the remote warehouse)

  • $git remote -v: see which local warehouses and which remote warehouses remain linked
  • $git remote add origin [git remote warehouse address]: establish a connection between the local warehouse and the remote warehouse. Origin is a random link name, which can be changed to any name you want, but it is generally used
  • $git remote rm origin: delete associated information
  • $git pull origin master: you'd better pull it before submitting to see if there is any new content
  • $git push origin master: submit the local code to the remote warehouse (you need to enter the github account and password)
  • $git clone [git remote warehouse address] [alias, which can not be set. The default is the warehouse name]
    //= > the real project development process is: 1 The team leader or person in charge shall first establish a central warehouse The team members clone the remote warehouse and the default content locally based on git clone (solved three things: 1. Initialize a local warehouse git init 2. Keep an association with the corresponding remote warehouse git remote add 3. Pull the default content of the remote warehouse to the local git pull) 3 After each team member completes their own program, based on git add And get commit -m submit the local content to the history area, and finally upload it to the central warehouse through git push (before uploading, you'd better git pull to see if there are new content added by others)

NPM(node package manger)

NODE module management tool. According to npm, we can quickly install and uninstall the resources we need (for example, jQuery, Vue, Vue router...)
node -v: View node version
npm -v: View npm version

Module management based on npm

https://www.npmjs.com/ Based on npm, it is from npmjs Download and install on COM platform
npm install xxx: install modules in the current project (node_modules)
npm install xxx -g: install the module in the global environment
npm i xxx@1.0.0 : installs the module with the specified version number
npm view xxx versions > xxx. version. JSON: view the version information of a module (output to the specified JSON file)
npm init -y: initializes the configuration list of the current project (the name of the project folder cannot contain capital letters, Chinese characters or special symbols. After successful creation, a package.json file list will be generated in the current project. dependencies: Production dependency module: required for project development and deployment, devdependences: development dependency module: required only during development, scripts: configure local executable commands)
npm i xxx --save: save the module to the production dependency list
NPM I XXX -- save dev: save the module to the development dependency list
npm install: run the environment and install the required modules according to the list
npm root -g: view the global installation module directory
npm uninstall xxx :
npm uninstall xxx -g: uninstall installed modules

Whole project process (start of new project)

1. Create a project folder
2. Use it as a new warehouse for code management (you can clone the remote warehouse based on $git clone)
3. Initialization module configuration list package json($ npm init -y)
4. Install the required modules ($NPM I jQuery) bootstrap@3 Less) [@ 3 stands for installing the last version of bootstrap 3]
5. Start writing code
6. In development: you may need to configure commands locally to complete some functions (for example, when compiling LESS files, you need to configure npm executable commands, find scripts in the configuration list package.json, and add the compilation code you need)

"scripts": {
    "lesscly": "lessc css/index.less css/index.min.css -x" //This section is used to compile index The less file is converted into an executable css. When compiling, execute npm run lesscly to execute the command
  }

7. In the development process, we need to manage files based on git: when the corresponding historical version is produced and submitted to the temporary storage area, historical area and remote warehouse, many files in the project do not need to be uploaded, such as node_modules, ideas... We produce a gitignore ignore file
8. We don't submit node every time git is submitted_ Modules, so in team collaborative development, whenever we pull down the program, we need to run the environment and execute: $npm install, according to the package in the project Install all missing modules according to the dependency information in JSON

Variable promotion

After the browser opens up the stack memory for code execution, the code does not execute from top to bottom, but does a lot of things. One of them is to declare and define all the keywords with var and function in the current scope in advance (this is the variable lifting mechanism)

  • Only declare var a with VaR// If it is only declared without assignment, it is undefined by default
  • Not only the declaration with function, but also defined / / definition is actually assignment. To be precise, it is to associate a variable with a value
console.log(a);//=> a=undefined
var a=12;
var b=a;
b=13;
console.log(a);//=> a=12


console.log(sum(10,20));//=>30
function sum(n,m){
  return n+m;
}

//Function expression method. Since var is used to create sum, the variable promotion stage will only declare variables without assignment, so the function cannot be executed without value (this method is more commonly used in real projects because this operation is more rigorous)
console.log(sum(10,20));//=>Unexpected typeerror: sum is not a function
var sum=function(n,m){
  return n+m;
}

The difference between with VaR and without var

/* => Differences under global scope
 *
 * Without var, it is equivalent to setting an attribute a to the global object window
 * window.a=13;
 */
a=13;
console.log(a); //=> 13

/*
 * Stack memory variable storage space
 *      b  
 * With var: a variable b (global variable) is declared under the global scope, but the variable declared under the global scope is also equivalent to adding a corresponding attribute to the window (only the global scope has this feature)
 */

 var b=14;
 console.log(b);//=> 14
 console.log(window.b);//=> 14

The difference between let/const and var

1. There is no variable promotion mechanism for let and const

Among the six ways to create variables, only var and function have variable promotion, and let, const, import and class do not have variable promotion mechanism
2.var can be declared repeatedly, but let cannot be declared repeatedly
In the same scope / execution context, if you use the var and function keywords to declare variables and declare them repeatedly, it will not have an impact (after the declaration for the first time, it will not be repeated if it is encountered later)
However, let or const cannot be used. The browser will check whether the variable already exists in the current scope. If it does, an error will be reported if it is declared again

=> Before the browser opens up stack memory for code top-down execution,There are not only variable lifting operations,There are many other operations,There is another operation called'lexical analysis 'Or call'Lexical detection',The function is to detect whether the current code to be executed will exist'grammar'error,If an error occurs,The code will not execute,Direct error reporting
  console.log(1); =>Due to the following syntax error,So no output
  let a=12;
  console.log(a); =>Due to the following syntax error,So no output
  let a=13;  =>Uncaught SyntaxError: Identifier 'a' has already been declared
  console.log(a); =>Due to syntax error on the upper side,So no output


  console.log(1); =>The 1 here can be output
  console.log(b); =>Uncaught ReferenceError: Cannot access 'a' before initialization
  let b=12;

  =>The so-called repetition refers to,No matter what method was adopted before,As long as this variable exists in the current stack memory,We use let/const Declaring this variable again is a syntax error(In the lexical analysis stage,Not during code execution)
  console.log(a);
  var a=12;
  let a=13; =>Uncaught SyntaxError: Identifier 'a' has already been declared
  console.log(a);

fn();
function fn(){console.log(1);};
fn();
function fn(){console.log(2);};
fn();
var fn=function(){console.log(3);};
fn();
function fn(){console.log(4);};
fn();
function fn(){console.log(5);};
fn();

/* global scope
 * 1.Variable promotion phase No matter whether the condition in if is true or not, the variable promotion stage must be executed first
 *    var a =>At this time, a is undefined, a global variable a is created, and an attribute value window. Is given to window a
 * 2.Execute code phase
 *   [property] in [object]:Check whether the current property belongs to this object and return a boolean result
 */
console.log(a); => undefined
if(!('a' in window)){   => 'a' in window===true  !true===false
  var a = 14;
}
console.log(a); => undefined
/* global scope
 * 1.Variable promotion stage
 *    However, if the 'function' is in the 'condition judgment', no matter whether the condition is true or not, the variable will only be promoted in the variable promotion stage and 'will not be assigned', and it will be promoted and assigned in the old version browser. However, in the new version browser, in order to be compatible with the strict syntax specification of ES6, the function in the condition will only be declared in advance in the variable promotion stage and will not be assigned
 * 2.Execute code phase
 *   
 */
//fn(); =>  Uncaught typeerror: FN is not a function, because FN in the if judgment, the lifting variable stage has no assignment, so FN () at this time is equivalent to a declared variable rather than a function. Then we comment it out and execute the following code
if('fn' in window){  
  fn();   => 'fn' in window===true Conditions established,The first thing I came in was to fn assignment,Then execute the code,So this fn()Can output,The content is hello!
  function fn(){
    console.log('Hello!');
  }
}
fn(); => Hello!

Self executing function

For example, (fn([parameter]) {}) ([argument]), you can also + fn([parameter]) {} ([argument]), fn([parameter]) {} ([argument])! fn([formal parameter]) {} ([actual parameter]), - fn([formal parameter]) {} ([actual parameter]), preceded by (), +, - just to avoid syntax errors and have no other special meaning
Since the self executing function itself has no function name, it does not promote variables

f=function(){return ture;} => global variable,window.f=...
g=function(){return false;} => global variable,window.g=...
~function(){  => Self executing function
  /*
   * Function execution forms a private scope
   * 1.Variable promotion function g(Because in if In condition,So just raise the variable,Without assignment)
   * 2.Code execution
  /
  if(g()&&[]==![]){   => Uncaught TypeError: g is not a function Because at this time g()Not yet a function,Therefore, the conditions are not tenable,So it will report an error,The following code will no longer be executed
    f=function(){return false;}
    function g(){return true;}
  }
}();
console.log(f());
console.log(g());

Let can solve the problem of temporary dead zone during typeof detection (let(const, class, import) is more rigorous than var(function))

console.log(a); =>Uncaught ReferenceError: a is not defined

console.log(typeof a); =>'undefined'This is an example of the browser BUG,because a No definition,Should report an error

console.log(typeof a); =>Uncaught ReferenceError: Cannot access 'a' before initialization
let a;

Variable promotion under private scope

console.log(a,b);
var a=12;
var b=12;
function fn(){
  console.log(a,b);
  var a=b=13;
  console.log(a,b);
}
fn();
console.log(a,b);

console.log(a,b,c);
var a=12,
    b=13,
    c=14;
function fn(a){
  console.log(a,b,c);
  a=100;
  c=200;
  console.log(a,b,c);
}
b=fn(10);
console.log(a,b,c);

Global and private variables

If global variables and private variables point to the same address, they are related (it is wrong to say that global variables and private variables have nothing to do)

var ary=[12,23];
function fn(ary){
  console.log(ary);
  ary[0]=100;
  ary=[100];
  ary[0]=0;
  console.log(ary);
}
fn(ary);
console.log(ary);

Scope and scope chain

The scope has been defined since the function was created
Under which scope (N) the current function is created, the parent scope of the scope (M) formed by function execution is N, which has nothing to do with where the function is executed, but only with where it is created

var n=1;
function fn(){
  var n=2;
  function f(){
    n--;
    console.log(n);
  }
  f();
  return f;
}
var x=fn();
x();
console.log(n);

Closure scope

  • Create function

    • Open up a heap memory and store the code in the function as a string
    • Assign the heap memory address to the function name or variable name
    • Where is the function created? Who is the parent scope found during execution
  • Function execution

    • Form a new private stack memory (one at a time, and there will be no impact between multiple)
    • Formal parameter assignment & variable promotion
    • Code execution (take out the code string in the heap memory and execute it line by line)
    • Scope chain mechanism: when a variable is encountered, first see whether it is a private variable (the formal parameters and variables declared in the private stack memory are called private variables). If it is private, you can operate your own variables. If it is not private, you can search according to the superior scope until the global scope is found
    • Closure protection mechanism: there is no necessary relationship between private variables and external variables, which can be understood as being protected by private stack memory
  • Stack memory free problem

    • Function execution will form a stack memory (allocate a space from the memory). If the memory is not destroyed and released, it will easily lead to stack memory overflow (memory is full and the computer is stuck). The release of heap memory is one of the core knowledge of learning JS
  • Heap memory free

    • Creating a reference type data value will generate a heap memory. If the currently created heap memory is not occupied by other things (the browser will find the reference of each memory when it is idle, and the unused memory will be recycled and released), it will be released
    let obj ={
      name:'Xiao Wang';
    }
    let oop=obj;
    => here obj and oop All occupy the heap memory of the object,Want to free heap memory,You need to disassociate variables and values manually(null Null object pointer)
    obj=null;
    oop=null;
    
  • Stack memory

    • The global scope formed by opening the browser is stack memory
    • The private scope formed by manually executing functions is stack memory
    • The block scope based on let/const in ES6 is also stack memory
    • ...
  • Stack memory release

    • Global stack memory: it will be destroyed when the browser page is closed or refreshed
    • Private stack memory: generally, as long as the function is executed, the private stack memory will be destroyed and released. However, once something in the stack memory (usually the heap address) is occupied by something outside the private scope, the current stack memory cannot be released and destroyed immediately. Closure in the market: the private stack memory formed by function execution that cannot be destroyed, This is the closure Others believe that as long as the private stack memory is formed to protect the variables inside, this mechanism is the closure mechanism
    function x(){
      return function(){...}
    }
    let f=x();
    
  • Two functions of closure

    • Protection (private variables are not necessarily related to the outside world)
    • Save (form stack memory that cannot be destroyed, and private variables and other information in it are also saved)
var i=5;
function fn(i){
  return function(n){
    console.log(n+(++i));
  }
}
var f=fn(1);
f(2);
fn(3)(4);
fn(5)(6);
f(7);
console.log(i);

var i=20;
function fn(){
    i-=2;
    return function (n){
        console.log((++i)-n);
    }
}
var f=fn();
f(1);
f(2);
fn()(3);
fn()(4);
f(5);
console.log(i);

var a=9;
function fn(){
	a=0;
	return function(b){
		return b+a++;
	}
}
var f=fn();
console.log(f(5));
console.log(fn()(5));
console.log(f(5));
console.log(a);

Explain in detail the two functions of closures (protection and preservation)

From the perspective of performance, we should reduce the use of closures in real projects (because closures will produce non released stack memory, and excessive use will lead to memory overflow or reduce performance)

  • protect

    • 1.JQuery(JQ) front end is a very classic class library: it provides a large number of methods for developers to use = > at the same time, in order to prevent global variable pollution (explanation: after importing JQ, there are a large number of methods in it. If these methods are not protected, the methods written by users are easy to conflict with the method names in JQ, and the conflict can be understood as global variable pollution), Methods and variables in JQ need to be protected with closures
  • preservation

this problem

The subject of function execution (not the context): it means who executes the function, so the subject of execution is who. This is very difficult to understand. Therefore, when you meet this later, think of a sentence: "what you think is what you think."
Bind a method to an event of an element. When the event triggers the execution of the method, this in the method is the element itself of the current operation
How to determine the topic: if there is a point in front of the method, this is the content before the method. If there is no point, this is window or undefined (the difference between strict and non strict)

var name='Lao Wang';
function fn(){
  console.log(this.name);
};
var obj={
  name:'Lao Li',
  fn:fn
};
obj.fn();  => obj Executive,be this by obj,Export Lao Li
fn();  => In non strict mode,fn()by window.fn(),be this by window,Export Lao Wang
var fullName='language';
var obj={
  fullName:'javascript',
  prop:{
    getFullName:function(){
        return this.fullName;
    }
  }
};
console.log(obj.prop.getFullName()); =>this:obj.prop  return obj.prop.fullName  undefined
var test=obj.prop.getFullName;  
console.log(test());  =>this:window  return window.fullName  language
var num=10;
var obj={num:20};
obj.fn=(function(num){
  this.num=num*3;
  num++;
  return function(n){
    this.num+=n;
    num++;
    console.log(num);
  }
})(obj.num);
var fn=obj.fn;
fn(5);
obj.fn(10);
console.log(num,obj.num);

The meaning of logical or and non in the case of assignment

A | B: first verify whether the value of a is true or false. If a is true, return the value of a; otherwise, return the value of B
A & & B: first verify whether the value of a is true or false. If a is true, return the value of B; otherwise, return the value of A
&&Priority of is higher than||

var foo='hello';
(function(foo){
  console.log(foo);  => private variable hello
  var foo=foo||'world'; hello||world => Return private variable hello 
  console.log(foo);  => private variable hello
})(foo); => Here is the global variable foo Value of'hello'A formal parameter passed to a function as an argument
console.log(foo);  => global variable hello

Construct prototype pattern (orthodox object-oriented)

I can create custom classes and corresponding instances, and build a complete set of object-oriented model

function CreatePerson(name,age){
  this.name=name;
  this.age=age;
}


=> CreatePerson('Zhang San',18) Here is normal function execution


let person1=new CreatePerson('Li Si',20);
=> new CreatePerson()Connection between execution and ordinary function execution
=> 1.new This method of execution is called'Constructor execution mode',At this time CreatePerson Not just a function name,go by the name of'class',And the result returned(Assign to person1 of)Is an object,We call it'example',And what appears in the function body this These are all examples

instanceof: used to detect whether an instance belongs to this class

The instance instanceof class returns true, otherwise false
Limitations: 1 It is required that the detected instance must be an object data type, and the basic data type cannot be detected based on it
typeof can detect basic data types, but reference data types cannot be specifically distinguished. null is detected as object, which is just complementary to instanceof

Literal creation method (also an instance of number class, or you can call the built-in common method)

let n=10;
console.log(n.toFixed(2));
console.log(typeof n);   => 'number'

Constructor creation mode (the created instance is of object type)

let m=new Number('10');
console.log(typeof m);  => 'object'
console.log(m.toFixed(2));
=> The operations related to the instance must be this.xxx=xxx,because this Is an instance created by the current class
=> Private variables are not necessarily associated with instances

function Fn(n){
  let m=10;
  this.total=n+m;
  this.say=function(){
    console.log(this.total);
  };
}
let f1=new Fn(10);
let f2=new Fn(20);
let f3=new Fn;
console.log(f1.m);
console.log(f2.n);
console.log(f1.total);
f2.say();
console.log(f1===f2);

Prototype and prototype chain model

=> Perform steps(new Execution also executes the class as an ordinary function,Of course, there is also class execution)
=> 1.Create a private stack memory
=> 2.Formal parameter assignment&Variable promotion
=> 3.The browser creates an object(This object is a new instance of the current class),And let the this Point to this instance object(In constructor mode,In method this Is an instance of the current class)
=> 4.Code execution
=> 5.We don't set it ourselves return Return case,The browser will return the currently created instance object by default


function Fn(){
  this.x=100;
  this.y=200;
}
let f1=new Fn();
let f2=new Fn();

1. The value of each function data type has an inherent attribute: prototype. The attribute value of this attribute is an object ('used to store instance public attributes and methods')
Function data type

  • Ordinary function
  • Classes (custom and built-in)

2. In the prototype object, there is a built-in attribute constructor, which stores the current function itself

Fn.prototype.constructor===Fn  => true

3. The value of each object data type also has an inherent attribute: proto, which points to the 'prototype of the class'
Object data type

  • Common object, array, regular, Math, date, class array, etc
  • Instances are also values of object data types
  • The value of the prototype prototype property of the function is also the object data type
  • Functions are also values of object data types

Prototype chain lookup mechanism

1. Find your own private attribute first. If yes, call it for use. If not, continue to find it
2. Based on__ proto__ Find the method (Fn.prototype) on the prototype of the class. If it is not found, continue based on__ proto__ Look up until you find object Up to prototype

hasOwnProperty

'hasOwnProperty' is used to detect whether a property name is a private property of the current object
'in' is used to check whether this attribute belongs to an object (whether it is a private attribute or a public attribute, as long as it is its attribute, the result is true)

let ary=[1,2,3];
console.log('0' in ary); => true
console.log('push' in ary); => true
console.log(ary.hasOwnProperty('0')); => true
console.log(ary.hasOwnProperty('push')); => false push It is a public attribute, not a private attribute

console.log(Array.prototype.hasOwnProperty('push')); => true Public or private depends on the relative who comes. There are private attributes in your heap,Need based__proto__(__proto__This property is in IE Not available in browser,edge except)The search is public

Encapsulates a method for detecting public attributes

=>Expand one hasPubProperty Method is used to detect whether the property is public

        =>stay object Bind one on hasPubProperty Method of
        Object.prototype.hasPubProperty=function(prop){
            =>First, you must determine whether the passed in attribute is number,string,boolean etc.
            let propAry=['number','string','boolean'];
            let resProp=typeof prop;
            if(!propAry.includes(resProp)){
                return false;
            }

            =>Then judge whether the passed in attribute is the attribute of the object
            let x=prop in this;

            =>Then judge whether the passed in property is the private property of the object
            let y=this.hasOwnProperty(prop);

            =>If it is a property of the object and is not a private property, return true,Otherwise return false

            if(x===true&&y===false){
                return true;
            }else{
                return false;
            }
        };

        console.log([].hasPubProperty('push')); //true

Extend the built-in class method (the previous array is written to the prototype of the class)

!function (){
  function myUnique(){
  //Create an empty object to receive the contents of the circular array
  let obj={};

  //Loop through the incoming array, define an item, and take the contents of the incoming array as the attribute name and attribute value
  for(let i=0;i<this.length;i++){
    let item=this[i];
    //If the attribute name is not equal to undefined, the description is repeated
    if(obj[item]!==undefined){
      this[i]=this[this.length-1];  //Swap this item with the last one
      this.length--;   //Array length minus one
      i--;
      continue;
    }
  obj[item]=item;
  }
  //Ensure that the returned result is still an instance of Array, so that we can use chain methods (chain writing needs to ensure that each returned result must be an instance of the current class)
  return this;
}

Array.prototype.myUnique=myUnique;//Put the method on the prototype of the Array class
}() 

call\apply\bind in Function

They are all three public methods provided on the prototype
Each function can call these methods
These methods are used to change the point of this in the function

call

window.name='WINDOW'
let obj={name:'OBJ'};
function(){
  console.log(this.name);
}
fn() =>  this:window(Strict mode yes undefined,Yes in non strict mode window)

fn.call(obj); => this:obj

Syntax: functions call([context],[params1]…)
Function. Was found when the function was based on the prototype chain lookup prototype. Call this method and execute it. When the call method is executed, the following operations are completed

  • Let the current function execute
  • Change this point in the function to the first argument passed to call
  • Pass the remaining arguments passed to call to the current function as parameter information
  • If no parameters are passed when the call method is executed, the this point in the function is window in non strict mode and undefined in strict mode

Write a built-in call method based on native JS (different from the browser's own)

~function(){
    function call(context){
      context = context || window;
        let args=[],
        result;
        for(let i=1;i<arguments.length;i++){
            args.push(arguments[i]);//Give each of the passed parameters to the args array
        }
        //We need to turn this in fn into context
        //Add an attribute name (custom one) to the context object so that the attribute value corresponding to the attribute name is fn1
        context.myIndex=this;//This is who call s this
        result=context.myIndex(...args);//Expand the operator, execute the method first, and then pass each item in the array as a parameter
        delete context.myIndex
        return result;
    }
    Function.prototype.call=call;
}();

apply

Like the call method, it executes the function and changes the direction of this inside. The only difference is that the passed parameter forms are different
call is passed one by one, and apply is passed an array

bind

Like call and apply, it is also used to change the direction of this, but bind does not execute this function when changing the direction

ES6 basic syntax

Let / const (the difference between them)

Difference between let and var: let does not have variable promotion (in the current scope, it cannot be used before let declaration)
let cannot be declared repeatedly in the same scope
let solves the typeof transient deadband
In the global scope, using let to declare variables will not add attributes to window
let will have a block level scope (curly braces other than objects can be regarded as a block level private scope)

Arrow function (newly added function creation method in es6)

const fn=([Formal parameter])=>{
  //Function body
}
fn([Argument])

Arrow functions are created in the form of function expressions, so there is no variable promotion, and functions can only be executed after creation
If there is only one formal parameter, parentheses can be omitted
If there is only one statement in braces and it is return, the braces can be omitted
The arrow function does not have arguments, but it can obtain the set of arguments based on the remaining operator (...), and ES6 supports setting default values for formal parameters
The arrow function does not have its own this, and its this is the this in its own execution context

Deconstruction assignment in ES6

Let the left side have the same structure as the right side, so as to quickly get the content we need (the deconstruction and assignment of arrays and objects are mostly used in the project)

const ary=[10,20,30,40,50];
const [n,m,...x]=ary;  => ...x Extension operator:Store the rest in x In array,But this expression can only appear at the end
console.log(n,m,x); => 10 20 [30,40,50]
======================================================

const ary=[10,[20,30,[40,50]]];
const [n,[,,[,m]]]=ary;
console.log(n,m); => 10 50
======================================================

const obj={
  name:'Lao Wang',
  age:18,
  sex:'boy',
  friends:['Lao Li','Lao Liu','Lao Chen','Lao Zhang']
}

const {name,age,xingbie}=obj
console.log(name,age,xingbie)  => Lao Wang 18 undefined  Structure assignment of object,The property name on the left must remain the same as that on the right(The order can be arbitrary)To get the corresponding value,If you have to define the attribute name yourself, you can sex:xingbie

const {name,sex:xingbie,age}=obj; 
console.log(name,xingbie,age) => Lao Wang boy 18
======================================================
const {
  name,
  friends:[firstFrineds]
}=obj;  
console.log(name,firstFrineds) => Lao Wang and Lao Li
======================================================

const data={
  'code':0,
  'data':{
      'today':'2021-07-02',
      'data':[{
          'date':'2021-07-01',
          'number':'10',
          'weekday':'\u661f\u671f\u4e09'
      },{
          'date':'2021-07-02',
          'number':'20',
          'weekday':'\u661f\u671f\u56db'
      }]
  }
}

const {
  code,
  data:{
    today,
    data:calenderData
  }
}=data;

console.log(code,today,calenderData); => 0 "2021-07-02" Two pieces of data in the following objects

calenderData.forEach((item)=>{
  let weekday=item.weekday,
  date=item.date;
  console.log(weekday,date);
})

'...' in ES6

Extension operator (mostly used in Deconstruction assignment)
Expand operator (mostly used in passing arguments)
Residual operator (mostly used in receiving arguments)

=> Extension operator
const ary=[10,20,30];
const [n,...m]=ary;
console.log(n,m) => 10 [20,30]


=> Expand operator
const ary=[10,20,30];
let min=Math.min(...ary);  =>amount to Math.min(10,20,30)

=> Array cloning(Shallow cloning)
const cloneAry=ary.slice(0);

const cloneAry=[...ary]

=> Object cloning(Shallow cloning)
const obj={
  name:'Lao Wang',
  age:18,
  sex:'male'
}

const cloneObj={...obj,age:20,sex:'female'}
console.log(cloneObj); => {name: "Lao Wang", age: 20, sex: "female"}


=> Residual operator
const fn=(n,...m)=>{
  //n:10   ...m:[20,30]
}
fn(10,20,30);

Create a class using class in ES6

=> Creating classes in a traditional way
function Fn(){
  this.x=100;
}
Fn.prototype.getX=function(){
  console.log(this.x);
}
var f1=new Fn();
f1.getX();

// It can also be executed as an ordinary function
Fn();

// Fn can also be regarded as an ordinary object
Fn.queryX=function(){}
Fn.queryX();


=>ES6 in class Class creation
 class Fn{
   constructor(n,m){
     this.x
   }

   getX{
     console.log(this.x)
   }  //=>Public methods written on prototypes

   static queryX(){};//=>Add static in front to set the key value pair with the current Fn as a normal object
   static z=100;
   y=100; //Set private properties for the instance
 }

Template string in ES6

Back quotes ${}

let year=2021,
month=07,
day=02;

let res=`Today is ${year}year ${month}month ${day}day`;
console.log(res);  =>Today is July 2, 2021

Method of borrowing array from class array

=> Implement a summation method
function sum(){
  const ary=[];
  let total=null;
  ary.forEach.call(arguments,(item)=>{   //Point this in the array to arguments
    total=total+item; 
  })

  return total;
}

sum(10,20,30,40); //100

Interaction between client and server

What do users experience when they enter the web address in the address bar of the browser window and finally see the page?

  • 1.URL address resolution
  • 2.DNS domain name resolution
  • 3. Establish a TCP connection with the server
  • 4. Transfer the client information to the server (send HTTP request)
  • 5. The server gets and processes the request (HTTP response content)
  • 6. The server renders the content returned by the server
  • 7. Disconnect TCP from the server

URI/URL/URN

URL(Uniform Resource Locator): a uniform resource locator that finds the corresponding resource according to the address
URI(Uniform Resource Identifier): uniform resource identifier. URN and URL are subsets of URIs
URN(Uniform Resource Name): uniform resource name, which generally refers to some internationally common (standard) names (such as the number of international uniform distribution)

What should a complete URL contain

https://www.bilibili.com/video/BV1rV411n72v?p=294&spm_id_from=pageDriver

  • Protocol (http: / /)

    • http hypertext transfer protocol can transfer not only text, but also media resource files (or stream files) and XML format data
    • https is more secure than http. Generally, websites involving payment will use this protocol (s:ssl encrypted transmission)
    • ftp file transfer protocol is generally used to upload local files to the server
  • Domain name (www.bilibili.com)

    • Top level domain QQ com
    • First level domain name www.qq.com com
    • Secondary domain name sports qq. com
    • Third level domain name KBS sports. qq. com
    • . com international domain name
    • . cn Chinese domain name
    • .com.cn
    • . edu Education
    • gov government
    • . io blog
    • . org organization
    • . net system class
  • Port number (: 80): the value range of port number is 0-65535. Port number is used to distinguish different items on the same server

    • http default port number: 80
    • https default port number: 443
    • ftp default port number: 21
    • If the project uses the default port number, we don't need to add the end slogan when writing the address. The browser will add it by default when sending the request
  • Request resource path name (/ video/BV1rV411n72v)

    • Default path or name (xxx.stu/ if the resource name is not specified, the server will find the default resource. Generally, the default resource names are default.html, index.html, etc., which can be configured on the server)
    • Pay attention to the address processing of pseudo URLs (URL rewriting technology is to increase the optimization of SEO search engines. Dynamic URLs generally cannot be searched by search engines, so we need to make the dynamic URLs static. At this time, we need to rewrite the URLs)
      https://item.jd.hk/2688449.html => https://item.jd.hk/index.php?id=2688449
  • Question mark parameter information (? P = 294 & spm_id_from = pagedriver)

    • There are many ways for the client to pass information to the server
      • URL address question mark parameter
      • Request message transmission (request header and request body)
    • Information can also be exchanged between different pages, for example, from list to details
  • HASH value (#...)

    • It can also act as a means of information transmission
    • Anchor location
    • Implement routing control based on HASH (different HASH values show different components and modules)

    DNS server domain name resolution

    DNS server: a domain name resolution server, which stores records related to the domain name < = > server's extranet IP
    When we send a request, the so-called DNS resolution is actually to find the external IP of the corresponding server on the DNS server according to the domain name

    DNS optimization

    • DNS cache (generally, after the first resolution, the browser establishes the cache by default. The time is very short, only about one minute)
    • Reduce the number of DNS resolutions (the domain names and servers that we need to send requests in a website can be reduced as much as possible)
    • DNS prefetch: at the beginning of page loading, DNS resolves the information of other domain names (servers) that need to be accessed in the current page in advance. Later, it can be loaded into the specific content without resolution

    Establish TCP connection (three handshakes)

    HTTP message

    • Request message: all contents transmitted from the client to the server through the transmission protocol are called request message
    • Start line
    • Request header
    • Request subject
    • Response message: all contents returned by the server to the client through the transmission protocol are called response messages
    • HTTP status code
    • Response header
    • Response subject
    • HTTP message: request message + response message

    HTTP status code

    1-5, three digits

    • 200 OK: successful
    • 201 CREATED: generally used to tell the server to create a new file, and the status code returned after the server is successfully created
    • 204 NO CONTENT: for some requests (such as PUT or DELETE), the server does not want to process them. It can return empty content and notify them with 204 status code
    • 301 Moved Permanently: permanent redirection
    • 302 Moved Temporary: temporary transfer was basically implemented with 302 long ago, but now it is mainly done with 307
    • 304 Not Modified: sets the http negotiation cache
    • 307 Temporary Redirect: temporary redirect, mainly used for server load balancing, etc
    • 400 Bad Request: wrong parameter passed to server
    • 401 Unauthorized: no access
    • 404 Not Found: the requested address is incorrect
    • 500 Internet Server Error: unknown server error
    • 503 Service Unavailable: server overload

Four steps of AJAX

1. Create an AJAX instance
Let XHR = XMLHttpRequest / / = > IE6 the following uses new ActiveXObject()

2. Open the URL (configure the information to send the request)
method:http request method
URL: request address (API interface address)
ASYNC: set synchronous or asynchronous. By default, true is asynchronous and false is synchronous
User name: the user name passed to the server
User pass: the password passed to the server
xhr.open('GET','./json/xxx.json',true)

3. Listen to the ajax status. When the status is X, get the content of the server response
Ajax status code: 0 1 2 3 4

4. Send the request (the content of the request body is placed in send)

http request mode

  • get series requests (take more from the server and give less)
    • get
    • Delete: generally used to tell the server to delete information from the server
    • head: just want to get the content of the response header and tell the server that the content of the response body is not wanted
    • options: tentative request. Send a request to the server to see if it can be received and returned
  • post series requests (take less from the server and give more)
    • post
    • Put (corresponding to delete): tell the server to store the information I give to the server (generally used for files and large data contents)

It is best to use the corresponding request (semantic) in real projects

The get series is generally used to obtain information from the server, and the post series is generally used to send information to the server, but both can transfer information to and obtain information from the server, but the two are more and less

How does the client pass information to the server?

  • Question mark reference XHR open(‘GET’,’./getdata?xxx=xxx&xxx=xxx’)
  • Set request header XHR setRequestHeader([key],[value])
  • Set request body XHR Send (main content)

How does the server return information to the client?

  • Set response header
  • Set the response body (most of the information is returned through the response body)

The essential difference between get series and post series
The way to pass the get series to the server is generally: question mark to parameter
The post series is generally passed to the server by setting the request body
1.get delivers less content to the server than post because the URL has a maximum length limit (ie: 2K, Google: 4-8k), and the excess is intercepted by the browser
2.get will generate a cache (this cache is uncontrollable). Because of the requested address (especially the information transmitted by the question mark), the browser sometimes thinks that you will take the last information as the last requested information. Therefore, we need to remove this cache by adding a random number after the address
3. Compared with post, get is not secure (although neither of them is secure): get passes parameters based on question marks, which is easy to be hijacked by URL, while post is the request subject, which is not easy to be tampered with

AJAX status code

Get status code: XHR readyState

  • UNSEND 0: not sent (create an xhr, initial status is 0)
  • Open 1: opened (XHR. Open executed)
  • HEADERS_RECEIVED 2: the response header information has been returned to the client (after sending the request, the server will return the response header and response body information in turn)
  • LOADING 3: wait for the server to return the response body information
  • DONE 4: the response subject information has been returned to the client

Seven methods in Ajax

  • abort() interrupt request information
  • getAllResponseHeaders() gets all response header information
  • getResponseHeader() gets the response header information
  • open()
  • send()
  • setRequestHeader() sets the request header information
  • overrideMimeType() reformats Mime type

Promise

let promiseExample=new Promise((resolve,reject)=>{
  //The asynchronous tasks we want to operate are generally stored here. The tasks successfully execute the resolve function and fail to execute the reject function
})

=> promise The first argument to must pass a function,We call it executor
=> When we new One promise When the instance object of executor implement
=> promise Not only will executor Execute and give executor Pass two parameters,resolve Function sum reject function
=> resolve Function representation promise The asynchronous event processed was successful,Then put promise The status of is changed to fulfilled
=> reject Function representation promise The asynchronous event processed failed,Then put promise The status of is changed to rejected
=> promise.prototype There are three common methods,Respectively then,catch,finally
=> then Is before the asynchronous operation is completed,Add two methods to the event pool(What needs to be done for success and failure),Wait until the asynchronous operation completes,Again according to resolve perhaps reject To execute the corresponding event,catch Represents a capture error,finally Whether he succeeds or fails, he will perform the things set by himself

let promiseExamp=new Promise((resolve,reject)=>{
setTimeOut(()=>{
let ran=Math.random();
ran<0.5?reject(ran):resolve(ran)
},1000)
})

promiseExamp.then((success)=>{
console.log('success' + success)
},(error)=>{
console.log('failed '+ error)
})

promiseExamp.catch((message)=>{
console.log('failed '+ message)
})

promiseExamp.finally(()=>{
console.log('I'll show up regardless of success or failure! '
})

Topics: Javascript ECMAScript html Ajax