ES6 summary of important knowledge points

Posted by Alka-Seltzer on Wed, 22 Sep 2021 14:36:43 +0200

ES6

1 ES6 getting started

Ruan Yifeng recommended books: https://es6.ruanyifeng.com/#docs/reference

1.1 INTRODUCTION

ECMAScript standard is abbreviated as ES6, also known as ES2015. It stipulates that future ECMAScript standards are changed every year and are uniformly named by the year (June of each year)

1.2 block level scope

Variables declared at the block level cannot be accessed outside the code block. This is called the block level scope, also known as the syntax scope

Block level scopes can be created inside functions and code blocks {}

1.3 let and const

{
    var a=2;

    let b=10;
     variable b Can only be accessed within a code block
    console.log(a)//2
    console.log(b)//10
}

console.log(a)//2
console.log(b)//b is not defined

let features:

  • Let and const do not have variable promotion. The reason is that the area before let and const is called temporary dead zone, and the variable of var has variable promotion
  • The variables declared by let and const no longer belong to window and cannot be accessed through the variable name of window. The variables declared by var belong to window
  • Variables cannot be declared repeatedly at the same level using block level scope (variables declared by let cannot be repeated)

const features:

  • Const and let have the same characteristics as let except that const is a declared constant
  • const declared constants can only be assigned when declared
  • const declared constants cannot be modified

Exercise: Click to output the current subscript

*{margin: 0;padding: 0;}
ul{list-style: none; margin: 50px auto; width: 200px;}
li{
    width: 200px;
    height: 50px;
    background-color: rgb(126, 235, 116);
    margin: 10px 0;
}
<ul>
    <li></li>
    <li></li>
    <li></li>
</ul>

ES5:

var li=document.getElementsByTagName('li');
for(var i=0;i<li.length;i++){
    li[i].index=i;
    li[i].onclick=function(){
        console.log(this.index)
    }
}

ES6:

//General function version
var li=document.getElementsByTagName('li');
console.log(li)
for(let i=0;i<li.length;i++){
    li[i].onclick=function(){
        console.log(i)
    }
}

//Arrow function version
var li=document.getElementsByTagName('li');
console.log(li)
for(let i=0;i<li.length;i++){
    li[i].onclick=()=>{
        console.log(i)
    }
}

2. New features of ES6 function

2.1 functions with default values

The biggest feature of JavaScript functions is that when passing parameters, the number of parameters is not limited. In order to make the function robust, default values are generally processed inside the function

ES6 adds the support of "default value" from the syntax level (the default value can be number, string, expression or even function)

ES5:

function fun(a,b){
    a= a || 10;
    b= b || 30;
    console.log(a,b)//10 30
}
// fun(10,30)//10 30
fun(0,0)//If a bug occurs, you get 10,30

ES6:

function demo(a=10,b=30){
    console.log(a,b)//10 30
}
// fun(10,30)//10 30
demo(0,0)//0,0

2.2 default values affect arguments

In ES5, arguments is used to receive all incoming arguments, and an array is returned

ES5:

//In non strict mode, the re assignment of formal parameters will affect the values in arguments
function fun1(a,b){
    console.log(arguments)//[3,6]
    console.log(arguments[0]===a)//true
    console.log(arguments[1]===b)//true

    a=33;
    b=20;
    console.log(arguments[0]===a)//true
    console.log(arguments[1]===b)//true
    console.log(arguments)
}
fun1(3,6)

//Strict mode
function fun2(a,b){
    //Using strict mode, the formal parameters are re assigned, which will not affect the values in arguments
    'use strict'
    console.log(arguments)
    console.log(arguments[0]===a)//true
    console.log(arguments[1]===b)//true

    a=33;
    b=20;
    console.log(arguments[0]===a)//false
    console.log(arguments[1]===b)//fasle
    console.log(arguments)
}
fun2(3,6)

fun1() result:

fun2() result:

ES6:

//The default values of parameters in ES6, whether in strict mode or non strict mode, are the same as those in ES5
function fun3(a,b=1){
    console.log(arguments)
    console.log(arguments[0]===a)//true
    console.log(arguments[1]===b)//true

    a=33;
    b=20;
    console.log(arguments[0]===a)//false
    console.log(arguments[1]===b)//false
}
fun3(3,6)

fun3() result:

Note:

The purpose of "use strict" is to specify that the code is executed under strict conditions.

You cannot use undeclared variables in strict mode.

2.3 the default parameter is expression

The default value of a parameter can be an expression or a function call

function getValue(){
    return 5;
}
function add(first,seconed=getValue()){
    return first+seconed;
}
var res = add(1)
console.log(res)//6

//Note: getValue() is only called when the add function is called without passing in the second parameter
//Since the default value can be an expression, we can use the previous parameter as the default value of the subsequent parameter
//Otherwise, it is not true (the following parameter definition expression cannot be used as the parameter default value)
function add(first=2,seconed=first+1){
    return first + seconed;
}

var res = add(3);
console.log(res)//7

var res = add();
console.log(res);//5

2.4 remaining parameters (key points)

ES6 Provides a more convenient way to handle unnamed parameters, called residual parameters
 Syntax:
    function fun(a,...b){
        [The remaining parameters are received with three points, and the remaining parameters are put into the array b in]
    }
function run(a,b,...c){

    //Arguments receives all the arguments passed in
    console.log(arguments)//[1, 2, 3, 4, 5, 6, 7, 8]

    //... the remaining parameters receive only the remaining formal parameters
    console.log(a,b)//1 2
    console.log(c)// [3, 4, 5, 6, 7, 8]
}
run(1,2,3,4,5,6,7,8)

be careful:

  • A function can have at most one remaining parameter, which must be placed at the end of all formal parameters
  • Although there are remaining parameters, arguments still exist
  • The remaining parameters appear in * * "function declaration" *

2.5 extension operator (emphasis)

1. The extension operator breaks up an array or object

var arr=[1,2,3,4,5,6]
//Math.max() can only receive numbers one by one
var res=Math.max(1,2,3,4,5)
console.log(res)//6

//In ES5, you need to switch objects through apply to obtain the maximum value
var res =Math.max.apply(Math,arr)
console.log(res)//6

//In ES6, the... Extension operator can obtain the number of arrays one by one, which is equivalent to breaking up arrays or objects
console.log(...arr)//1 2 3 4 5 6
console.log(Math.max(...arr))//6

2 extension operator joins two arrays

var arr1=['walnut','seven seven'];
var arr2=[1,2,3,4,5]

//ES5
var newArr=arr2.concat(arr1)
console.log(newArr)//[1, 2, 3, 4, 5, "walnut", "77"]

//ES6
var arr3=[1,2,3,4,5,...arr1]
console.log(arr3)//[1, 2, 3, 4, 5, "walnut", "77"]

3 use of extension operator inheritance

 var People={
            nation:'China',
            city:'Beijing'
        }
 var student={
     //Inherit parent class
     ...People
 }
console.log(student)//{nation: "China", city: "Beijing"}

People.city='Shanghai'
console.log(People)//{nation: "China", city: "Shanghai"}
console.log(student)//{nation: "China", city: "Beijing"}


var People={
    nation:'China',
    city:'Beijing',
    foods:['Roasted Duck','wonton','Facet']
}
var student={
    //Inherit parent class
    ...People
}
People.foods.push('Diaoxiao Noodles')
console.log(People.foods)// ["roast duck", "hand copying", "noodles", "noodles with knife"]
console.log(student.foods)// ["roast duck", "hand copied", "small noodles", "sliced noodles"]

As can be seen from the above example, the inheritance of the... Extension operator is a shallow copy operation

2.6 structure assignment (key points)

ES6 allows us to extract variables from arrays or objects according to a certain pattern for assignment, which is called structure assignment

In essence, structure assignment belongs to "pattern matching". As long as the patterns on both sides of the equal sign are the same, the variables on the left will be given corresponding values

//For the assignment of ES5, take out the value of the array and assign it to the corresponding variable
var arr=[1,2,3];
var a=arr[0];
var b=arr[1];
var c=arr[2];
console.log(a,b,c)

//The structure assignment of ES6 array is mainly based on the same subscript
var [a,b,c]=[10,20,30];
console.log(a,b,c);//10 20 30

var [d,,e]=[10,20,30]
console.log(d,e);//10 30
//The structure assignment of an object mainly depends on the property name and method name
//Only when the variable name and the attribute name have the same name can the correct value be obtained, regardless of the order
var People={
    nation:'China',
    city:'Beijing',
    foods:['Roasted Duck','wonton','Facet']
}

var {nation,city}=People
console.log(nation,city)//Beijing China

var {city,nation}=People
console.log(nation,city)//Beijing China

//Common usage of structure assignment
function demo({city}){
    //Equivalent to {city}=People
    console.log(city)//Beijing
}
demo(People)

3 arrow function (key)

3.1 syntax

ECMAScript6 allows the use of arrow = > to define functions. The syntax is as follows

(arg1,arg2...)=>{
    Function body
}

Example 1:

  • When there is only one formal parameter of the arrow function, the () containing the formal parameter can be omitted, and can not be omitted in other cases
  • When there is only one line of code after the arrow function and the parenthesis {} is not widened, the return function is provided
//Ordinary function
//ES5
var fun=function(){
    console.log(111)
}
//ES6
var fun=()=>{
    console.log(111)
}
fun()
//Functions with parameters
var fun1=function(a){
    return a
}
var fun1=(a)=>{
    return a
}
//When there is only one formal parameter of the arrow function, the () containing the formal parameter can be omitted, and can not be omitted in other cases
//When there is only one line of code after the arrow function and the parenthesis {} is not widened, the return function is provided 
var fun1=a=>a

var res=fun1(3)
console.log(res)//3

Example 2:

Special case: return returns an object

//Special case: return returns an object

//ES5
var fun2=function(){
    // var obj={
    //     name: 'walnut',
    //     age:16
    // }
    return {
        name:'walnut',
        age:16
    };
}

//ES6
var fun2=()=>{
    // var obj={
    //     name: 'walnut',
    //     age:16
    // }
    return {
        name:'walnut',
        age:16
    };
}

//In special cases, you have to add a () to the object {}
var fun2=()=>({ name:'walnut',age:16})

var res=fun2();
console.log(res);//{name: "walnut", age: 16}

Example 3:

Self executing using arrow functions

//Self executing using arrow functions

//ES5
(function(){
    console.log('Anonymous function')
})();

//ES6
(()=>{
    console.log('Anonymous function')
})();

3.2 there is no this binding in the arrow function

In ES5, the binding of this is a troublesome problem. If you don't pay attention to it a little, you can't achieve the desired effect, because in ES5, the binding of this has nothing to do with the defined location, but only with the location of its call

this refers to the problem in ES5:

  • In a normal function, this refers to the global object window
  • In a normal object, this refers to the current object
  • In the constructor, this refers to the instantiated object
  • When apply ing, call ing, and bind ing switch objects, this refers to the switched object

There is no this binding in the arrow function (it does not mean that ES6 does not have this). The definition of this is only related to the defined scope and has nothing to do with the location of the call

// Writing method of ES5
btn.onclick = function(){
    // Output after 2s of timer
    setTimeout(function(){
        console.log(this)//window
    },2000)

    // ES6 arrow function
    btn.onclick = function(){
        setTimeout(()=>{
            console.log(this);//btn button
        },2000)
    }

The arrow function can make this point fixed, which is conducive to object-oriented encapsulation of callback functions

//Constructor
function Dog(name,color){
    this.name = name;
    this.color = color;
}

Dog.prototype.doSomething = function(){
    
    document.onclick =()=>{
    	console.log(this)//Dog
    	console.log(this.color)//yellow
    }
}
			
var dog = new Dog('chinese rhubarb','yellow');
console.log(dog)
dog.doSomething()//yellow

Summary:

1. Note that this point in the arrow function is fixed, not because this is bound inside the arrow function. In fact, this is not bound inside the arrow function, so this inside the function is this of the external code block

2. As a throw after use function, the arrow function cannot be used as a constructor, that is, the arrow function cannot be used in the way of new

3. Since this in the arrow function has nothing to do with the scope of the function, call, apply and bind cannot be used to rebind this

4. The arrow function does not have its own arguments object, but the arrow function can use an external arguments object

4 object extension

In js, almost all types are objects, so using objects well is very important to improve js performance

4.1 object category (understanding)

Ordinary objects have js all default behaviors

Some internal behaviors of exotic object s are different from the default

Standard objects are objects defined in ES6, such as Array Date. They may be ordinary objects or special objects

Built in object refers to the existing objects when js' running environment starts to run. Standard objects are built-in object s

4.2 literal syntax extension (key)

4.2.1 simplify attribute initialization

var name ='seven seven'
var age=16

var obj={
    name:name,
    age:age
}
console.log(obj)//{name: "77", age: 16}

//improvement
var name ='seven seven'
var age=16

var obj={
    name,
    age
}
console.log(obj)//{name: "77", age: 16}


Note: in ES6 If the object attribute name is the same as the local variable name, the colon and value can be omitted in the assignment and the attribute can be written directly

When the attribute in the object literal has only the attribute name, the js engine will look for whether there is a variable with the same name as the attribute name within its scope. Shorthand can make the object literal more concise.

4.2.2 abbreviations of object methods

var name ='seven seven'
var age=16

var obj={
    name,
    age,
    //Object method abbreviation
    play(){
        console.log('corpse')
    }
}
obj.play()//corpse

4.2.3 attribute name advance

var key1='adas_sd'
var key2='aacc_a'

var obj={
    key1:12312,
    key2:123456,
    
	//The variable name as the attribute name needs to be enclosed in brackets
    [key1]:12312,
    [key2]:123456,   
}
console.log(obj)//{key1: 12312, key2: 123456, adas_sd: 12312, aacc_a: 123456}

4.3 new methods in object

4.3.1 Object.is()

Object.is() determines whether two objects are equal. This method compensates for the strange behavior of congruence (= =). It will be determined to be equal only when their types and values are equal

console.log(+0 == -0);//true
console.log(+0 === -0);//true
console.log(Object.is(+0,-0));//false

console.log(NaN == NaN)//false
console.log(NaN === NaN)//false
console.log(Object.is(NaN,NaN))//true

Generally, the effect of Object.is() is the same as that of = = = (congruent). The difference between them is the judgment + 0 -0 NaN in strange situations

4.3.2 Object.assign()

Object.assign() is mainly used to simplify object mixin g, which refers to introducing an object into another object's attribute or method (copy)

var obj={
    name:'walnut',
    age:16,
    love:['seven seven','Zhong Li','Smoke Fei']
}

var newObj={}

//Copy obj object to newObj object
Object.assign(newObj,obj)
console.log(newObj)//{name: "walnut", age: 16, love: Array(3)}


obj.love.push('Condensing light')
console.log(obj.love)//["Qi Qi", "Zhong Li", "Yan Fei", "Ning Guang"]
console.log(newObj.love)//["Qi Qi", "Zhong Li", "Yan Fei", "Ning Guang"]
//As described above, the Object.assign() method is a shallow copy


//Object.assign() can copy multiple objects at the same time
var obj2={
    name:'timely rain',
    love:'Lei Jun'
}

//newObj has multiple providers
Object.assign(newObj,obj,obj2)

console.log(obj2)//{name: "sweet rain", love: "Lei Jun"}
console.log(newObj)//{name: "sweet rain", age: 16, love: "Lei Jun"}
 Multiple providers,This means that if the following providers have the same name, the properties of the previous providers will be overwritten

be careful:

This copy of Object.assign() is a shallow copy

Shallow copy refers to when the attribute value of the copied attribute is not the basic data type (array \ object)

Copying is just copy ing the memory address of the object

5 new functions of string

5.1 find string

In ES5, indexOf() lastIndexOf() is used to find strings

ES6 adds three new methods to find strings

includes(text,index) Find whether the string is in text and return boolean Value. existence->true  non-existent->false
startsWith(text,index)Whether the text begins with the specified character,return boolean value  
endsWith(text,length)Returns whether the text ends with the specified character boolean value  

be careful:
length Represents the total length, calculated from 1
index Indicates that the subscript is calculated from 0
var str ='Big Qiu is ill. Two Qiu look, three Qiu collect medicine and four Qiu boil';

var res=str.includes('Great mound');
console.log(res)//true
var res=str.includes('Great mound',2);//Find from subscript 2
console.log(res)//false

var res=str.startsWith('Great mound');
console.log(res)//true
var res=str.startsWith('Two hills',5);
console.log(res)//true


var res=str.endsWith('Great mound');
console.log(res)//false
var res=str.endsWith('Great mound',3);
console.log(res)//true

5.2 repeat() method

//repeat(n) the number of times the previous string is repeated
var str='walnut';
var res=str.repeat(3)
console.log(res)//Walnut walnut

5.3 template literal of string (key)

The template literal quantity is mainly the improvement of the following functions of ES6 for js:

Multiline string

Basic string formatting: the ability to convert variables in a string to values

Escape HTML: the ability to escape strings and insert HTML safely

1. Grammar

Use a pair of inverse parentheses `` (Tab Right above the key) To represent the template literal

2. Multiline string

//Template literal of string``

//report errors
// var str = 'walnut
// timely rain
// Zhong Li '

var str=`walnut
 timely rain
 Zhong Li`
console.log(str)//Output in original text format

3. String replacement (key)

//Substitution of strings
var obj={
    name:'walnut',
    age:16,
    area:'Li Yue'
}

//ES5 string splicing
var str=obj.name+'this year'+obj.age+'Years old, living in'+obj.area
console.log(str)//Walnut is 16 years old and lives in Liyue

//ES6 template literal
var str=`${obj.name}this year ${obj.age}Years old, living in ${obj.area}`
console.log(str)//Walnut is 16 years old and lives in Liyue

4. Template label

The real strength of template literals lies in template labels. A template label can be converted to template literals and returned as the final value (the label must be specified before the template)

The template tag is not a template, but a special form of function call. The tag refers to the function, and the template string immediately following is its parameter

//Template label
alert `Liyue people`//Equivalent to alert('liyue man ')

5. Self defined template label

function myTag(str,...value){
    //str gets characters other than variables
    console.log(str)//["", "this year", "", raw: Array(3)]

    //The remaining parameters get all the variables in the string and return them as an array
    console.log(value)//["walnut", 18]
}
var name = 'walnut'
var age = 18
myTag`${name}this year ${age}`;

6 new basic type Symbol

There are six data types in ES5:

  • number numeric type
  • String string type
  • Boolean boolean type
  • Undefined undefined type
  • Null null type
  • Object object type (function)

ES6 adds a new data type Symbol

Solution: in ES5, the attribute of our object is a string, which is easy to be rewritten. There is no way to create private properties, only through encapsulation. Symbol creates a unique value

6.1 create Symbol

Symbols are special in basic data types and need to be created through the global function Symbol

//Create Symbol
var names= Symbol();
console.log(typeof name)//symbol

var obj={
    [names]:'walnut',
    age:16
}

console.log(obj)//{age: 16, Symbol(): "walnut"}
var a1=Symbol();
var a2=Symbol();
console.log(a1==a2)//false
console.log(a1===a2)//false

var obj={
    [Symbol()]:'the one and only'
}
console.log(obj)//{Symbol(): "unique"}
//At this time, Symbol() recreates another unique value. If the attribute in obj is not assigned, it is undefined
console.log(obj[Symbol()])//undefined

When creating a symbol, a string is allowed to be passed in parentheses. The string is only used to distinguish between symbols and has no practical effect

var s1 = Symbol('seven seven')
var s2 = Symbol('seven seven')
console.log(s1 === s2)//false

be careful: s1 s2 Is a unique value
 If attribute name is used symbol Type, which can ensure that the attribute names are unique and will not conflict with other attribute names

6.2 identifying symbols

Symbol is a basic data type. You can use the typeof operator to identify whether it is a symbol.

If the symbol variable is directly output on the console, it is difficult to distinguish. It is recommended to add a parameter (string) to describe the created symbol as a distinction when creating the symbol variable

6.3 Symbol as object attribute (key)

//symbol as the attribute of the object
var user=Symbol('user');
var age=Symbol('age');

//Method 1
var person={
    // You need to add brackets to the variable name as an attribute
    [user]:'walnut'
}
console.log(person)//{Symbol(user): "walnut"}

//Method 2
person[age]=16
console.log(person)//{Symbol(user): "walnut", Symbol(age): 16}

var sex;
person[sex]='female'
for(var key in person){
    console.log(person[key])//female
    console.log(`Properties: ${person[key]},Attribute value: ${person[key]}`)//Attribute: female, attribute value: Female
}//The above example shows that when Symbol is used as the attribute name, for...in or for...of traversal cannot be used

be careful:

1. When symbol is used as the attribute of an object, you can only add or access it with [] instead of point syntax

2. When symbol is used as the object attribute name, the attribute is still a public attribute, not a private attribute. But you cannot traverse through for... in or for... of at this time

6.4 traversal of symbol attribute name

//Traverse Symbol Object.getOwnPropertySymbols(): return the symbol properties in all objects as an array
var res=Object.getOwnPropertySymbols(person)
console.log(res)//[Symbol(user), Symbol(age)]
console.log(res[0])//Symbol(user)
console.log(person[res[0]])//walnut

//Reflect.ownKeys(): returns the attributes in all objects as an array
var keys=Reflect.ownKeys(person);
console.log(keys)//["undefined", Symbol(user), Symbol(age)]

Note: when the value of Symbol is used as the attribute name, it will not be traversed by the conventional method (for... in for... Of). We use this feature to create some non private methods for the object, but we want to use them only internally

6.5 use of symbol. For() and Symbol.keyFor()

Symbol. For (string): each time you create a symbol, you will search the global environment for the value of the symbol with the string as the parameter. If you find it, you will return the symbol. If you can't find it, you will create a symbol and register it in the global environment

//The difference between Symbol and Symbol.for

var a1=Symbol('walnut')
var a2=Symbol('walnut')
console.log(a1==a2)//false

//Every time Symbol.for() is created, it will search the global environment for the existence of the Symbol with the string as the parameter. If it exists, it will directly return the created Symbol. If it does not exist, it will recreate the Symbol and register with the global environment

var b1=Symbol.for('seven seven')
var b2=Symbol.for('seven seven')
console.log(b1==b2)//true

//Symbol.keyFor(symbol) returns a key registered with the global symbol
//Only registered symbols will return strings
var res=Symbol.keyFor(b1)
console.log(res)//seven seven

The difference between Symbol.for() and Symbol():

1. Symbol.for() will get the same result every time for the same string, but Symbol() will not have the same result and will be created every time.

2. Symbol() will create a new symbol every time and will not register with the global; Symbol.for() creates a new symbol only when the global cannot be found and registers it with the global

6.6 Symbol summary

//1. Create unique values
//2. Add a unique value to the object attribute, first create and assign a value, and then add []
//3. As an object attribute, it cannot be traversed by for... In
//4. Every time a symbol is created, it will not be registered to the global. Symbol.for() finds it first and then registers it

7 Set

set itself is a constructor

//establish
var set =new Set()
//add to
set.add('walnut')
//length
console.log(set.size)

7.1 create a Set set and add elements

var set=new Set();
console.log(set)//Set(0)
console.log(typeof set)//object

//Add element (add)
set.add('walnut')
console.log(set)//Set(1) {walnut}

//Set set length
console.log(set.size)//1

7.2 Set cannot add duplicate elements

set.add('a');
console.log(set);//{"a", "b"}
console.log(set.size);//2

Note: set judges whether two elements are equal through the Object.is() method (but = = = is used to judge + 0 - 0)

set.add(+0);
set.add(-0);
console.log(set)//{"a", "b", "c", 0}

exceptional case:

// In special cases, array and object reference types point to different memory spaces every time they are added
console.log(set.size)//1

set.add([])
console.log(set.size)//2
set.add([])
console.log(set.size)//3

7.3 array de duplication

var arr=[2,3,5,6,2,5,3]
var set =new Set(arr);
console.log(set)//[2,3,5,6]

7.4 judge whether a value is in Set

// Determine whether a value has() exists in the Set
var arrSet = new Set([2,3,4])
console.log(arrSet.has(5))//false
console.log(arrSet.has(2))//true

7.5 delete values in Set

Delete (value to be deleted)

clear() clears all values

var set= new Set([1,2,5,3,6,4])

//Deletes the specified value
set.delete(1)
console.log(set)//{2,5,3,6,4}

//Clear all values
set.clear()
console.log(set)//{}

7.6 Set traversal

Set traversal intelligence uses implicit iteration, that is, forEach

Supplementary knowledge points:
Array traversal (iteration):
    Show iterations  for loop
    Implicit iteration  forEach
    
Syntax:
Traversal array.forEach(function(val,key,ownerArr){
    //Formal parameters in forEach do not need to be passed in manually
     Parameter 1: val Represents the value of the element traversed
    Parameter 2: the key (subscript) of the array, but for Set Type, the value of the second parameter is the same as that of the first
    Parameter 3: the whole object currently traversed
})
set.forEach(function(val,key,ownARR){
    console.log(key,val,ownARR)
})//The output result has no subscript, so it cannot be traversed by for

//Change to arrow function
set.forEach((val,key)=>{
    console.log(`key Is: ${key},The value is: ${val}`)
})//The output result has no subscript, so it cannot be traversed by for

7.7 convert Set to array (emphasis)

Convert array to Set: when creating a Set, the array is passed in as a parameter

Convert Set to array: extend operator

//Array de duplication
var arr=[1,2,2,3,5,4,2,6]
var set=new Set(arr)

//Convert Set collection to array
// Method 1
var newArr=[...set]
console.log(newArr)// [1, 2, 3, 5, 4, 6]
// Method 2
console.log(Array.from(set))// [1, 2, 3, 5, 4, 6]

8 Map

In ES5, the properties of an object can only be strings

The map data type in ES6 contains a set of ordered key value pairs, where the key and value can be any data type

8.1 creating a Map

1. The Map constructor is also used for the creation of Map objects

2. set(key,value) is used for the storage key value pair of Map

3. get(key) to obtain the value corresponding to the specified key

var map=new Map();
console.log(map)//Map(0)

set(key,val) adds the specified key value pair

//set() adds attributes and attribute values
map.set(5,50)
map.set(true,'Full mark')
console.log(map)//Map (2) {5 = > 50, true = > "full score"}

get(key) gets the value corresponding to the specified key

//get() gets the value of the specified property
console.log(map.get(true))//Full mark

// If the key does not exist, undefined is returned
console.log(map.get(liyue));//undefined

8.2 three methods similar to map and Set

has(key) Judge given key Is it map Exist in
delete(key) delete map Specified in key And its corresponding value
clear() remove map All key value pairs in
size map Length of object

8.3 initialize Map (understand)

map can pass in an array like Set, but the passed in array must be a two-dimensional array (two-dimensional array)

var initMap = new Map([
    ['name','timely rain'],
    ['age','18'],
    [4,false]
])
console.log(initMap)//Map (3) {"name" = > "sweet rain", "age" = > "18", 4 = > false}
console.log(initMap.size)//3

8.4 Map traversal

var mapper=new Map();
    mapper.set(1,'walnut')
    mapper.set(2,'timely rain')
    mapper.set(3,'seven seven')
    mapper.forEach((val,key)=>{
  	console.log(`key:${key},val:${val}`)
})

for(var key of mapper){
    console.log(key)
}

9 Promise

9.1 getting started

1 what is promise?

promise is a solution for asynchronous programming. The traditional solutions are callback functions and events. promise is more reasonable than the traditional solutions. promise is proposed by the community.

  • In short, promise is a container containing an event that will end in the future. It is generally asynchronous.
  • promise is an object from which messages of asynchronous operations can be obtained. promise provides an agreed API. Various asynchronous operations can be processed in the same way.

Asynchronous synchronization?

Synchronization: the code is executed from top to bottom. You must wait until the previous code is executed before executing the following code. Most of the code in JS is synchronized.

Asynchronous: when the code is executed to an asynchronous code slice, the code behind the asynchronous code slice can be executed simultaneously with the asynchronous code slice.

JS common asynchronous:

  • Timer setTimeout, setInterval
  • Asynchronous requests for Ajax
  • animate() animation in jQuery
  • Promise in ES6

2 what are the three promise States?

Pending, resolved, rejected

3 promise advantages?

  • With the promise object, asynchronous operations can be expressed in the process of synchronous operations, avoiding layers of nested callback functions.
  • promise provides a unified API that makes asynchronous operations easier.

4 promise disadvantages?

  • Cannot cancel. Once created, it will be executed immediately. It cannot be cancelled halfway.
  • If the callback function is not set, promise will throw an error internally and will not be reflected externally.
  • In the pending status, you cannot know which stage it is currently in.

5 what are the characteristics of promise?

  • The state of the object is not affected by the outside world. promise represents an asynchronous operation.
  • There are three states: pending, resolved, and rejected.
  • Only the asynchronous result can determine the current state, and no operation can change the result.
  • Once the state changes, it won't change again. You can get the result at any time.
  • There are only two possible states of Promise: pending - > resolved or pending - > rejected. As long as these two states change, the result will solidify and will not change again, and the result will be retained all the time.

9.2 basic usage of promise

1 Grammar

ES6 specifies that Promise object is a constructor used to generate Promise instance

promise Basic usage syntax:

const promise = new Promise(function(resolve,reject){
    ...(some code)
    //Judge whether the asynchronous operation is successful
    if(/*Asynchronous operation succeeded*/){
        resolve(value)
    }else{
        reject(error)
    }
})
explain: promise Accept a function as an argument. The two arguments of the function are resolve and reject
 They have two functions( resolve and reject)from js Provided by the engine, you do not need to deploy it yourself
'resolve'The function: Promise Status from'hang in the air'become'complete',Called during an asynchronous operation
 And pass the result of the asynchronous call as a parameter
'reject'The function: Promise Status from'hang in the air'become'fail',Called during an asynchronous operation
 And pass the failed error information as a parameter

promise.then(function(value){
    //Function on success
},function(error){
    //Function on failure
})

explain:'then'Method can take two callback functions as parameters
 The first callback function is Promise Object becomes resolved Called when status
 The second callback function is Promise Object programming rejected Called when status
 The parameter of the second callback is optional and may not be provided

Promise.prototype.catch() receives the error thrown by promise

promise.catch(function(error){
    console.log(error)
})

2 random number cases

const promise=new Promise(function(resolve,reject){
    //Perform related asynchronous operations
    let num=Math.random()*2;

    // Var STR = num > 1? 'call succeeded': 'call failed';
    let flag=num>1 ? true: false;
    if(flag){
        // resolve('random number greater than 1 ')
        setTimeout(resolve, 1000,'Random number greater than 1');
    }else{
        // reject('random number less than 1 ')
        setTimeout(reject, 1000,'Random number less than 1');
    }
})
promise.then(
    function(data){
        //Executes when the resolve method is called
        console.log(data)
    },
    function(err){
        //Executes when the reject method is called
        console.error(err)
    })

3 online video loading cases

<div class="wrap"></div>
//Asynchronous request video

let url='https://f.video.weibocdn.com/002akCN7gx07PPZAb9cX01041201dcf50E010.mp4?label=mp4_1080p&template=1920x1080.25.0&trans_finger=d88af6227b88881484d2b59dfbafa136&media_id=4681647124316211&tp=8x8A3El:YTkl0eM8&us=0&ori=1&bf=3&ot=h&ps=3lckmu&uid=34tsO1&ab=3915-g1,5178-g1,3663-g0,5786-g0,966-g1,1493-g0,1192-g0,1191-g0,3601-g17,1258-g0&Expires=1631935806&ssig=fFWuNnPpa5&KID=unistore,video'

const promise=new Promise((resolve,reject)=>{
    let video=document.createElement('video');
    video.src=url
    video.controls='controls'

    //onloadedmetadata executes after the video metadata is successfully loaded
    video.onloadedmetadata=function(){
        resolve(video)
    }
    video.onerror=function(){
        reject('Video loading failed')
    }
})
promise.then((data)=>{
    console.log(data)
    let wrap=document.querySelector('.wrap');
    wrap.appendChild(data)
},(err)=>{
    console.error(err);
})
//Encapsulate the above code
function loadVideoSync(url){

    return new Promise((resolve,reject)=>{
        let video=document.createElement('video');
        video.src=url
        video.controls='controls'

        //onloadedmetadata is executed after metadata is loaded successfully
        video.onloadedmetadata=function(){
            resolve(video)
        }
        video.onerror=function(){
            reject('Video loading failed')
        }
    })

}

let promise=loadVideoSync(url)

promise.then((data)=>{
    console.log(data)
    let wrap=document.querySelector('.wrap');
    wrap.appendChild(data)
},(err)=>{
    console.error(err);
})

result:

success:

Failed:

4 request local json cases

function AjaxSync(url){
    return new Promise((resovle,reject)=>{
        //1. Create ajax objects
        let ajax=new XMLHttpRequest()

        //3. Monitoring status changes
        ajax.onreadystatechange=function(){
            if(ajax.readyState==4 && ajax.status==200){
                //4. Call resolve if successful
                // console.log(ajax.responseText)
                resovle(ajax.responseText)
            }
        }

        //2. Initiate get request
        ajax.open('get',url,true)
        ajax.send(null)
    })
}

const promise =AjaxSync('wearth.json')

promise.then((data)=>{
    var  data =JSON.parse(data)
    console.log(data)
},(error)=>{
    console.error(error)
})

wearth.json data:

{"desc":"OK","status":1000,"data":{"wendu":"22","ganmao":"The wind is strong and it is easy to catch a cold. Pay attention to protection.","forecast":[{"fengxiang":"north wind","fengli":"5-6 level","high":"High temperature 24℃","type":"Sunny","low":"Low temperature 11℃","date":"3 Sunday Saturday"},{"fengxiang":"north wind","fengli":"4-5 level","high":"High temperature 19℃","type":"Sunny","low":"Low temperature 8℃","date":"4 Sunday Sunday"},{"fengxiang":"No sustained wind direction","fengli":"breeze","high":"High temperature 21℃","type":"Sunny","low":"Low temperature 9℃","date":"5 Sunday Monday"},{"fengxiang":"No sustained wind direction","fengli":"breeze","high":"High temperature 21℃","type":"cloudy","low":"Low temperature 10℃","date":"6 Sunday Tuesday"},{"fengxiang":"No sustained wind direction","fengli":"breeze","high":"High temperature 24℃","type":"Sunny","low":"Low temperature 12℃","date":"7 Sunday Wednesday"},{"fengxiang":"No sustained wind direction","fengli":"breeze","high":"High temperature 23℃","type":"Sunny","low":"Low temperature 11℃","date":"8 Sunday Thursday"}]}}

The code needs to be run on the server. I use WampServer, copy the code to the www directory of WampServer, enter localhost in the browser url path, and then enter the corresponding code file. The output result is:

10 async asynchronous

ES2017 standard introduces async function to make asynchronous operation more convenient

In async syntax, you can specify that the function returns a callback function added by the then method. When the function is executed, once await is encountered, it will return first, wait for the asynchronous operation to complete, and then execute the statements after await

// Use of async
async function getData(){
    // let promise=new Promise(function(resolve,reject){
    //     setTimeout(resolve,2000, 'network request succeeded');
    // })
    return new Promise((resolve,reject)=>{
        setTimeout(resolve,2000,'Network request succeeded');
    })
}

async function showAsync(){
    let promise=getData();

    //await waits for the result of asynchronous execution.
    await promise.then((data)=>{
        console.log(data)
    },(error)=>{
        console.log(error)
    })

    //If await is not added above, '111' will be output directly, and 'network request succeeded' will be output after two seconds
    //If await is added to the above, the output '111' will not be executed until the above 'network request successfully' is completed
    console.log(111)
}
showAsync();

Various functions of async use functions

//Standard function
async funtion foo(){

}

//Function expression
var foo = async function(){
}

//Methods within objects
let obj = {
    async foo(){}
}

//Arrow function
const foo = async ()=>{}

Error handling mechanism of async

Sometimes, if the previous asynchronous operation fails without interrupting the subsequent asynchronous operation, you can put await in the try... catch structure. Then the second await will be executed regardless of whether the asynchronous operation is successful or not

Main function: the writing method used to prevent errors

Syntax:
try{
    Code to execute
}catch(error){
    //Error automatically get the failed error information
    console.error(error)
}
async function foo(){
    try{
        let value = await new Promise(fun)
        let data = await value.getData();
    }catch(error){
        console.error(error)
    }
}

Class 11

What is a class?

A general term for something

js is not an object-oriented language in the strict sense, because there is no concept of class in js.

Before ES5, instance objects were generated mainly through constructors (constructors are ordinary functions). This code style is quite different from the traditional object-oriented language.

ES6 provides a writing method closer to the traditional language, introducing the concept of class as a template to define the constructor. In ES6, class can only be regarded as a syntax sugar, and ES5 can complete most of its functions. Only class makes the object prototype pattern clearer and object-oriented.

11.1 basic use

//A constructor is defined in ES5
function Animal(name,color){
    this.name=name;
    this.color=color;
    this.say=()=>{
        console.log('Meow~')
    }
}

let dog=new Animal('millet','white')
console.log(dog)//Animal {name: "Xiaomi", color: "white", say: ƒ}

//Define a class in ES6
class  Person{
    constructor(name,age){
        this.name=name;
        this.age=age;
    }
    say(){
        console.log(`Hello, I'm ${this.name},I this year ${this.age}Years old!`)
    }

    //Note that there are abbreviations, such as:
    // constructor:function() {} directly omits': function '
    // say:function() {} omitted directly ': function'
}
let ming=new Person('pet name',16)
ming.say()//Hello, I'm Xiao Ming. I'm 16 years old!

11.2 privatization in class

Privatization method: can only be accessed internally

Public method: it can be accessed normally externally

Common methods:

Method 1: add before the method name_

Note that this method is only an industry rule. Programmers mark this method as a private method and hope that it will not be called when others use it. However, we can still access it externally

//ES6
class  Person{
    constructor(name,age){
        this.name=name;
        this.age=age;
    }
    say(){
        console.log(`Hello, I'm ${this.name},I this year ${this.age}Years old!`)
    }
    //Define private methods
    //Method 1, add before the method name_
    _goHome(){
        console.log(`${this.name}Ready to go home!`)
    }
}

Method 2: remove the private method

//ES6
class  Person{
    constructor(name,age){
        this.name=name;
        this.age=age;
    }
    say(){
        console.log(`Hello, I'm ${this.name},I this year ${this.age}Years old!`)
        //Method two: remove the private method and call it in the say() method.
        //Switch to the current instantiated object through apply, call and bind
        goHome.call(this)
    }
}
//Method 2: remove the private method
function  goHome(){
    console.log(`${this.name}Ready to go home!`)
}

let ming=new Person('pet name',16)
ming.say()//Hello, I'm Xiao Ming. I'm 16 years old!
          //Xiao Ming is going home!

Method 3: use Symbol (recommended)

//ES6
let gooHome=Symbol()
class  Person{
    constructor(name,age){
        this.name=name;
        this.age=age;
    }
    say(){
        console.log(`Hello, I'm ${this.name},I this year ${this.age}Years old!`)
        this[gooHome]()//?
    }
    [gooHome](){
        console.log('Internal method')
    }
}
let ming=new Person('pet name',16)
//Call the private method created by symbol()
ming[gooHome]()//Internal method

11.3 this point in class (understand)

If the class method contains this, it points to the instance of the class (the object instantiated by new) by default. Once the method is used alone, an error may be reported

class Demo{
    constructor(name){
        this.name = name;
    }
    print(){
        console.log(this.name)
    }
}

var demo = new Demo('walnut');
demo.print()//

// Structure assignment
let {print} = demo
// console.log(print)
// print() / / an error is reported

print Medium this Default pointing demo Instance, if used alone this Refers to the current operating environment

Solution: arrow function

class Demo{
    constructor(name){
        this.name = name;
        this.print = ()=>{
            console.log(this.name)
        }
    }
}

var demo = new Demo('walnut');
console.log(demo)
demo.print()

// Structure assignment
let {print} = demo
print()

11.4 inheritance in class (key)

class inherits mainly through the 'extends' keyword

class Animal{}
class Dog extends Animal{}

Inherit all properties of the parent class Person

class Person{
    constructor(name,age){
        this.name=name;
        this.age=age;
    }
    say(){
        console.log(`My name is ${this.name},I this year ${this.age}Years old!`)
    }
}
//Inherit all properties of the parent class Person
class stu extends Person{

}

var ming=new stu('Xiao Ming',16)
ming.say()//My name is Xiao Ming. I'm 16 years old!

Inherit all the properties of the parent class Person and add new properties

class Person{
    constructor(name,age){
        this.name=name;
        this.age=age;
    }
    say(){
        console.log(`My name is ${this.name},I this year ${this.age}Years old!`)
    }
}

class stu extends Person{
     // If subclasses do not need to add new properties, they do not need to write constructors
    constructor(name,age,score){
        super(name,age);
        this.score=score;
    }
    
    sayScore(){
        console.log(`${this.name}The result is ${this.score}branch`)
    }
    
    toSay(){
        //super and this are used to call the methods of the parent class
        super.say()
    }
}

var ming=new stu('Xiao Ming',16,98)
ming.toSay()//My name is Xiao Ming. I'm 16 years old!
ming.sayScore()//Xiao Ming scored 98 points

12 import and export

export export file
import Import file

Topics: Javascript ECMAScript