ES6 (ECMAScript6) - ES11 from introduction to immortality

Posted by simcoweb on Tue, 08 Mar 2022 07:06:32 +0100

ES6: ECMAScript6

I. new features of ES6

1.let variable declaration and declaration features

1.1 let

Let keyword is used to declare variables. Variables declared with let have the following characteristics:

let a;
let b,c,d;
let e = 100;
let f = 521,g= 'iloveyou',h = [];

1. Variables cannot be declared repeatedly

let star = 'Li Ge Xiao';
let star = 'Li Xiaoyao';

2. Block level scope, global function, eval

//if else while  for
{
    let girl = 'Zhao linger';
}
console.log(girl);

3. There is no variable promotion

console.log(song);
let song = 'Legend of fairy sword';

4. It does not affect the scope chain

{
    let school = 'Xianyi';
    function fn(){
        console.log(school);
    }
    fn();
}

1.2 cases

Requirement: click div to change the background color

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div  style="width: 50px;height: 50px; margin: 10px; border: 1px solid black; "></div>
    <div  style="width: 50px;height: 50px; margin: 10px; border: 1px solid green; "></div>
    <div  style="width: 50px;height: 50px; margin: 10px; border: 1px solid yellow;"></div>
</body>
<script>
    //Get div element object
    let items = document.querySelectorAll("div");
    for(let i = 0;i<items.length;i++)
    {
        items[i].onclick = function(){
            items[i].style.backgroundColor = 'pink';
       } 
    }
    console.log(windows.i)  //3 
    // When var=3, the click event starts to find the outer scope. If it cannot be found, it is windows i. At this time, it is 3. If it is let i, it has block level scope, so the I of each touch event is different.
</script>
</html>

 

1.3const

const keyword is used to declare constants. const declarations have the following characteristics:
(constant means that the object pointed to cannot be modified, but the internal properties of the object can be changed)

1. Be sure to assign initial value

const A;

2. General variables are capitalized (hidden rules)

const a = 100;

3. Constant value cannot be modified

SCHOOL = 'LIGEXIAO';

4. Block level scope

{
     const PLAYER = 'UZI';
}
console.log(PLAYER);

5. For the element modification of array and object, it does not count as the modification of constant, and no error will be reported

    const TEAM = ['UZI','MXLG','Ming','Letme'];
    TEAM.push('LGX');
    console.log(TEAM);

 6. Duplicate declarations are not allowed

const FRUIT = "apple" 
const FRUIT = "apple" // An error is reported and cannot be repeated

1.4 deconstruction assignment

ES6 allows you to extract values from arrays and objects according to a certain pattern and assign values to variables, which is called deconstruction assignment.
Usage scenario: if you frequently use object methods and array elements, you can use the form of deconstruction assignment;

1. Structure of array

const F4 = ['Li Xiaoyao','Lin Yueru','Zhao linger','Liu Jinyuan'];
let[li,lin,zhao,liu] = F4;
console.log(li);
console.log(lin);
console.log(zhao);
console.log(liu);

 2. Deconstruction of objects

const li = {
    name:'Li Ge Xiao',
    age:'18',
    sing:function(){
        console.log('June rain ');
    }
}
let{name,age,sing} = li;
console.log(name);
console.log(age);
console.log(sing);
sing();

be careful:

  • In {} of let{name,age,sing} = li, the variable name inside should be the same as the attribute name in the object
  • let {sing} = li can only get the sing method inside, and then call it through sing()

 2. Template string

A string declared with a pair of backquotes `, with the following characteristics:

 1. statement

let str = `A song of parting laughs at the Jianghu`;
console.log(str,typeof str);//A song laughs at the Jianghu string

2. Line feed can be used directly inside

let str = ` <ul>
                <li>Li Ge Xiao</li>
                <li>Li Xiaoyao</li>
                <li>Zhao linger</li>
            </ul>`;
console.log(str);

3. Variable splicing (replacement / insertion)

Use ${variable name} to locate the inserted element

let name = 'Li Ge Xiao';
let out =  `a song ${name}Jianghu`;
console.log(out);//A song of parting laughs at the Jianghu

3. Simplified writing of objects

ES6 allows variables and functions to be written directly in curly braces as attributes and methods of objects. This writing is more concise

let name = 'Li Ge Xiao';
let sing = function(){
    console.log('A song of parting roars in the Jianghu');
}

Original:

const cos = {
    name:name,
    sing:sing,
    ligexiao:function(){
        console.log('A song of parting roars in the Jianghu');
    }
} 

ES6:

const cos = {
    name,
    sing,
    ligexiao(){
        console.log('Walking is like water, without distractions');
    }
}

4. Arrow function

ES6 allows the use of arrows = > to define functions

Function declaration:

//  let fn = function() {
// 		...
//  }

let fn = (a,b) => {
	return a + b
}
// Call function
console.log(fn(2,3))  // 5

When the value of this is always declared under the static scope of this.1

function getName(){
    console.log(this.name);
}
let getName2 = ()=>{
    console.log(this.name);
}
window.name = 'Li Ge Xiao';
const school = {
    name :'LIGEXIAO',
}
//Direct call
getName();//Li Ge Xiao
getName2();//Li Ge Xiao

//Call method call
getName.call(school);//LIGEXIAO
getName2.call(school);//Li Ge Xiao

2. Cannot instantiate object as constructor

let Person =(name,age)=>{
    this.name = name;
    this.age = age;
}
let me = new Person('ligexiao','30');
console.log(me);//Uncaught TypeError: Person is not a constructor

3. The arguments variable cannot be used

let fn = () =>{
    console.log(arguments);//Uncaught ReferenceError: arguments is not defined
}
fn(1,2,3);

4. Abbreviation of arrow function
(1) Omit the parentheses. When there is only one formal parameter, the parentheses can be omitted.

// let add = (n) => {
// 	 console.log(n + n)
// }
// add(3)  // 6

// Abbreviation:
let add = n => {
	console.log(n + n)
}
add(3)  // 6

(2) Omit curly braces {} only if the function statement has only one statement. At this time, 'return' also needs to be omitted, and the result is the return value

let pow = n => n * n
console.log(pow(8))    // 64

Practice

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>8.Arrow function exercise</title>
    <style>
    #ad{
        width: 200px;
        height: 200px;
        background:blue;
    }
    </style>
</head>
<body>
    <div id="ad"></div>
    <script>
        let ad = document.querySelector("#ad");
        //1. Change element background color
        ad.addEventListener('click',function(){
            //timer
            setTimeout(()=>{
                //Modify background color
                this.style.backgroundColor = '#c00';
            },1000)
        })

        //2. Return even elements from the array
        const arr =[1,6,9,10,100,25];
        // const result = arr.filter(function(value){
        //     if(value%2===0)
        //     {
        //         return true;
        //     }
        //     else{
        //         return false;
        //     }
        // })
        
        // const result = arr.filter((value)=>{
        //     if(value%2===0)
        //     {
        //         return true;
        //     }
        //     else{
        //         return false;
        //     }
        // })

        // const result = arr.filter(value=>value%2===0);
        // console.log(result);//[6, 10, 100]

        //The arrow function is suitable for callbacks that have nothing to do with this, timers and array methods
        //The arrow function is not suitable for callbacks, event callbacks and object methods related to this

        // {
        //     name: 'Li Ge Xiao',
        //     getName:()=>{
        //         this.name;
        //     }
        // }
    </script>
</body>
</html>

The arrow function is suitable for callbacks that have nothing to do with this, timers and array methods

The arrow function is not suitable for callbacks, event callbacks and object methods related to this

5. Function parameter default value

ES6 allows assignment of initial values to function parameters

characteristic:

  1. Initial values can be assigned to formal parameters, and the general position depends on the back (hidden rule)
function add(a,b,c=12){
    return a+b+c; 
}
let result = add (1,2) 
console.log(result) // 15

If the above code does not assign an initial value to the formal parameter c, when executing add (1,2), the formal parameter c has no corresponding parameter and defaults to NaN, so the execution result of add (1,2) is NaN

 2. Combined with deconstruction assignment

function ap({host='127.0.0.1', username, password, port}){
    console.log(host,username,password,port)    // 
}
ap({
	host: 'localhost',
    username:'admin',
    password:'000000',
    port:3000
 })
 // Execution result: localhost admin 000000 3000

6. rest parameters

  • ES6 introduces the rest parameter, which is used to obtain the function arguments instead of arguments

  • rest parameters: in Is a prefix, such as the following args

Original arguments

function date(){
    console.log(arguments);
}
date('Li Ge Xiao','Li Xiaoyao','Zhao linger');//Arguments(3) [Li Ge Xiao ',' Li Xiaoyao ',' Zhao linger ', callee: ƒ, Symbol(Symbol.iterator): ƒ]

Now the rest parameter

function date(...arg){
    console.log(arg);
}
date('Li Ge Xiao','Li Xiaoyao','Zhao linger');//['Li Ge Xiao', 'Li Xiaoyao', 'Zhao linger']

The rest parameter must be placed at the end of the parameter

function fn(a,b,...arg){
    console.log(a);
    console.log(b);
    console.log(...arg);
}
fn(1,2,3,4,5,6,7);//1 
                    // 2
                    //3 4 5 6 7

7. Extension operator

Extension operator, The array can be converted into a comma separated sequence of parameters

const tfboys=['Jackson Yee','Wang Yuan','Juen-Kai Wang']
function show(){
    console.log(arguments) 
}
show(tfboys)    // A parameter array: [Yiyang Qianxi, 'Wang Yuan', 'Wang Junkai' '.
show(...tfboys) //0: "Yiyang Qianxi" 1: "Wang Yuan" 2: "Wang Junkai"

Application:

1. Combination of arrays

const arr1 = ['Li Xiaoyao','Li Ge Xiao'];
const arr2 = ['Lin Yueru','Zhao linger'];
// const arr = arr1.concat(arr2);// ['Li Xiaoyao', 'Li Gexiao', 'Lin Yueru', 'Zhao linger']
const arr = [...arr1,...arr2];
console.log(arr);//['Li Xiaoyao', 'Li Gexiao', 'Lin Yueru', 'Zhao linger']

 2. Cloning of arrays

const arr3 = ['Li Xiaoyao', 'Li Ge Xiao', 'Lin Yueru', 'Zhao linger'];
const arr4 = [...arr3];//['Li Xiaoyao', 'Li Gexiao', 'Lin Yueru', 'Zhao linger']
console.log(arr4);//['Li Xiaoyao', 'Li Gexiao', 'Lin Yueru', 'Zhao linger']

If there is reference type data in the array, the whole is a shallow copy; Otherwise, it is a full copy

const divs = document.querySelectorAll("div");
const divArr = [...divs];
console.log(divArr);// [div, div, div]

8. Symbol

grammar

Directly use Symbol() to create a new symbol type with an optional string as its description.

Symbol([description])

Description (optional) string type. The description of the symbol can be used for debugging, but not to access the symbol itself. Note that even if you pass in two identical strings, the resulting symbols are not equal.

const symbol1 = Symbol();
const symbol2 = Symbol(42);

Symbol() and symbol The difference between for() and

Symbol(): calling the same symbol multiple times will generate multiple symbols

Symbol.for(): call the same symbol multiple times, and only the first symbol will be executed

Symbol. The for (key) method will find the corresponding symbol from the symbol registry of the runtime according to the given key. If it is found, it will return it. Otherwise, create a new symbol associated with the key and put it into the global symbol registry.

Key: a string used as the key associated with a symbol in the symbol Registry (repeatable call)

Symbol.for accesses a global submbol table. If you have one, you can access the corresponding object. If not, you can recreate it

Symbol.keyFor() method:
This method gets the key corresponding to the Symbol value.

Global definitions get the value of symbol, but ordinary definitions can't

let cms = Symbol.for('lgx');//Get the value of symbol from the global definition
console.log(Symbol.keyFor(cms));//lgx
let lxy = Symbol('lxy');//Ordinary definitions are not available
console.log(Symbol.keyFor(lxy));//undefined

Original: (the content is the same. Only the first one can be read by using [] to read the content)

let user1 = 'Li Ge Xiao';
let user2 = 'Li Ge Xiao';
let grade = {
    [user1]:{js:100,css:89},
    [user2]:{js:50,css:26}
};
console.log(grade);

Now?

// let user1 = 'singing and laughing'// {js: 100, css: 89}
// let user2 = 'laugh at parting songs';
let user1 = {
    name:'Li Ge Xiao',
    key:Symbol(),
}
let user2 = {
    name:'Li Ge Xiao',
    key:Symbol(),
}
let grade = {
    [user1.key]:{js:100,css:89},
    [user2.key]:{js:50,css:26}
};
console.log(grade[user1.key]);//{js: 100, css: 89}

Symbol value and assignment shall be added with []

Private property

If you don't want to publish objects and properties to the outside, you can use symbol

Since any two symbols are not equal, they can be easily used to simulate private properties in JavaScript. Symbol ` will not appear in object Keys (), so unless you explicitly export a symbol or use object Getownpropertysymbols() function, otherwise other codes cannot access this property.

 Object.keys() returns the attribute key, but does not include attributes that cannot be enumerated
Reflect.ownKeys() returns all attribute keys

let symbol = Symbol("A song of parting laughs at the Jianghu");
let lgx = {
    name:'Li Xiaoyao',
    [symbol]:'Li Ge Xiao',
}
// for (const key in lgx) / / normal traversal cannot traverse the value of symbol
// {
//     console.log(key);
// }
// for(const key of Object.getOwnPropertySymbols(lgx)) {/ / can only traverse to symbol type
//     console.log(key);
// }
// for(const key of Reflect.ownKeys(lgx)) / / returns all attribute keys
// {
//     console.log(key);
// }

let site = Symbol('A song of parting roars in the Jianghu');
class User{
    constructor(name){
        this.name = name;
        this[site] = 'Li Ge Xiao';
    }
    getName(){
        return `${this[site]} ${this.name}`;
    }
}
let lxy = new User('The Incredible Hulk');
// console.log(lxy.getName());
// for(let key in lxy)
// {
//     console.log(key);
// }

ES6 introduces a new primitive data type Symbol, which represents unique values. It is the seventh data type of JavaScript language, which is a data type similar to string.

  • The value of Symbol is unique, which is used to solve the problem of naming conflict

  • Symbol value cannot be calculated with other data

  • The object properties defined by Symbol cannot be iterated by using the for... in loop, but you can use reflect Ownkeys to get all the key names of the object

characteristic:

  1. establish
//Create Symbol
let s = Symbol();
// console.log(s,typeof s);//Symbol() 'symbol'
let s2 = Symbol('Li Ge Xiao');
let s3 = Symbol('Li Ge Xiao');
console.log(s2===s3);//false
//Symbol.for creation
let s4 = Symbol.for("Li Ge Xiao");
let s5 = Symbol.for("Li Ge Xiao");
console.log(s4===s5);//true

 2. Cannot operate with other data (not computable and comparable)

let result = s+100;
let result = s>100;
let result = s+s;//Uncaught TypeError: Cannot convert a Symbol value to a number

3. Type of data

String, number, Boolean, array, object, Null, Undefined, Symbol

Application:

  1. Method 1 for adding methods to objects:
let game= {
    name:'Tetris',
    up:function(){
        console.log('Upward');
    },
    down:function(){
        console.log('down');
    }
}
//Declare an object
let methods = {
    up:Symbol(),
    down:Symbol(),
};
game[methods.up] = function(){
    console.log('I can change the shape');
}
game[methods.down] = function(){
    console.log('I can fall fast!!!');
}
console.log(game);//{name: 'Tetris', up: ƒ, down: ƒ, Symbol(): ƒ, Symbol(): ƒ}
console.log(game[methods.down]());//I can fall fast!!!

 2. Add method 2 to the object:

let  youxi = {
    name:'Li Ge Xiao',
    [Symbol('lgx')]:function(){
        console.log('A song of parting laughs at the Jianghu');
    },
    [Symbol('lxy')]:function(){
        console.log('Walking is like water, without distractions');
    }
}
console.log(youxi);//{name: 'Li Ge Xiao', Symbol(lgx): ƒ, Symbol(lxy): ƒ}

Want to read the contents of the Symbol method

let lgx = Symbol('lgx');
let lxy = Symbol('lxy');
let  youxi = {
    name:'Li Ge Xiao',
    lgx:function(){
        console.log('A song of parting laughs at the Jianghu');
    },
    lxy:function(){
        console.log('Walking is like water, without distractions');
    }
}
youxi.lxy()//Walking is like water, without distractions

symbol built-in properties

1.Symbol.hasInstance (self control type detection)

//Self control type detection
class Person{
    static [Symbol.hasInstance](param){
        console.log(param);
        console.log('I was used to test the type');
        return false;
    }
}
let o = {};
console.log(o instanceof Person);

 2. Symbol. Isconcapspreable (this attribute determines whether the current object can be expanded when it is used as a parameter of concat)

const arr = [1,2,3];
const arr2 = [4,5,6];
arr2[Symbol.isConcatSpreadable]=false;
console.log(arr.concat(arr2));

9. Iterator

Iterator is an interface that provides a unified access mechanism for various data structures. As long as any data structure deploys the iterator interface, it can complete the traversal operation.

ES6 creates a new traversal command for... of loop, and the iterator interface is mainly used for for... of consumption
Data with native iterator interface (can be traversed by for of)

 for ... of and for in

for(let v in xiyou){
    console.log(v);//0 1 2 3
}
//Use for Of traversal array
for(let v of xiyou){
    console.log(v);//Li Xiaoyao, Zhao linger, Lin Yueru, Liu Jinyuan
}

Iterator principle

  1. Create a pointer object that points to the starting position of the data structure
  2. When the next() method is called for the first time, the pointer automatically points to the first member of the data structure
  3. Next, keep calling next(), and the pointer moves back until it points to the last member
  4. Each call to next() returns an object containing the value and done attributes
const xiyou = ['Li Xiaoyao','Zhao linger','Lin Yueru','Liu Jinyuan'];
//Use for Of traversal array
// for(let v of xiyou){
//     console.log(v);// Li Xiaoyao, Zhao linger, Lin Yueru, Liu Jinyuan
//     for in saves the key name and for of saves the key value
// }
let iterator = xiyou[Symbol.iterator]();
//Call the iterator method of the object, done: true, pointer to the last, end
console.log(iterator.next());//{value: 'Li Xiaoyao', done: false}
console.log(iterator.next());//{value: 'Zhao linger', done: false}
console.log(iterator.next());//{value: 'Lin Yueru', done: false}
console.log(iterator.next());//{value: 'Liu Jinyuan', done: false}
console.log(iterator.next());//{value: undefined, done: true}
  • When the value of done is true, the loop is completed
  • When you need to customize the traversal array, you should think of the iterator

Practice

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>17.Iterator custom traversal object</title>
</head>
<body>
    <script>
    //Declare an object
    const people = {
        name:'Legend of fairy sword',
        stus:[
            'lixiaoyao',
            'zhaolinger',
            'lingyueru',
            'liujingyuan'
        ],
        [Symbol.iterator](){
            //Index variable
            let index = 0;
            let that = this;
            return {
                next:function(){
                    if(index < that.stus.length)
                    {
                        const result = {value:that.stus[index],done:false}
                        //Subscript self increment
                        index++;
                        //Return results
                        return result;
                    }
                    else{
                        return {value:undefined,done:true}
                    }
                }
            }
        }
    }
    for(let key of people)
    {
        console.log(key);
    }
    let iterator = people[Symbol.iterator]();

    console.log(iterator.next());
    console.log(iterator.next());
    console.log(iterator.next());
    console.log(iterator.next());
    console.log(iterator.next());

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

10. Generator

Generator function is an asynchronous programming solution provided by ES6. Its syntax behavior is completely different from that of traditional functions. It is a special function

A generator looks like a function, but it can return multiple times.
The difference between the generator and the function is that the generator is defined by function * (note the extra * sign), and in addition to the return statement, it can also be returned multiple times with yield.

Callback hell

setTimeout(()=>{
    console.log('1 second');
    setTimeout(()=>{
        console.log('2 second');
        setTimeout(()=>{
            console.log('3 second');
            setTimeout(()=>{
                console.log('4 second');
                setTimeout(()=>{
                    console.log('5 second');
                },5000)
            },4000)
        },3000)
    },2000)
},1000)
function * generator (){    //There is one between the function name and function* 
    yield 'Ears'      //yield is the separator of the function code
    yield 'tail' 
    yield 'That's strange' 
}
let iterator = generator() 
console.log(iteretor.next())  
//{value: 'ear', done:false} next() / / execute the first paragraph and return the value after yield
console.log(iteretor.next())  //{value: 'tail', done:false}
console.log(iteretor.next())  //{value: 'that's strange', done:false}
function * gen(){
    console.log(111);
    yield 'One has no ears';
    console.log(222);
    yield 'One has no eyes';
    console.log(333);
    yield 'That's strange';
    console.log(444);
}
let iterator = gen();
// iterator.next();//111
// iterator.next();//222
// iterator.next();//333
// iterator.next();//444

// console.log(iterator.next());
// console.log(iterator.next());
// console.log(iterator.next());
// console.log(iterator.next());

//ergodic
for(let v of iterator)
{
    console.log(v);111 One has no ears 222 one has no eyes 333 it's strange 444
}

1. Parameter transfer of generator function

The second time you call the next method, the argument passed in will return the result as the whole of the first yield statement

The argument passed in by the current next method will return the result as the whole of the previous yield statement

function * gen(args){
console.log(args) //AAA
let one = yield 111  //111 (assign the value returned by yield 111 to one)
console.log(one) //BBB
let two = yield 222 //222
console.log(two) //CCC
let three = yield 333 //333
console.log(three) //DDD
}

let iterator = gen('AAA') 
console.log(iterator.next()) 
console.log(iterator.next('BBB'))   //The BBB passed in next will be the return result of yield 111
console.log(iterator.next('CCC'))   //The CCC passed in next will be the return result of yield 222
console.log(iterator.next('DDD'))   //The DDD passed in next will be the return result of yield 333

 

2. Example 1: solve the callback problem by using the generator function

function one(){
    setTimeout(()=>{
        console.log('111')
        iterator.next()
    },1000)
}
function two(){
    setTimeout(()=>{
        console.log('222')
        iterator.next() 
    },2000)
}
function three(){
    setTimeout(()=>{
        console.log('333')
        iterator.next() 
    },3000)
}

function * gen(){
    yield one() //111
    yield two() //222
    yield three() /333
}

let iterator = gen() 
iterator.next() 

3. Example 2: simulating asynchronous data acquisition

Asynchronous programming: file operation, network operation (ajax,request) database operation timer

//Simulate obtaining user data, order data and commodity data
function getUsers(){
    setTimeout(()=>{
        let data = 'user data';
        iterator.next(data);
    },1000)
}
function getOrders(){
    setTimeout(()=>{
        let data = 'Order data';
        iterator.next(data);
    },1000)
}
function getGoods(){
    setTimeout(()=>{
        let data = 'Commodity data';
        iterator.next(data);
    },1000)
}

function * gen(){
    let users = yield getUsers();
    console.log(users);
    let orders = yield getOrders();
    console.log(orders);
    let goods = yield getGoods();
    console.log(goods);
}
let iterator = gen();
iterator.next();

11. Promise

Promise is a new solution for asynchronous programming introduced by ES6. Syntactically promise is a constructor used to encapsulate asynchronous operations and obtain the results of their success or failure.

 const p = new Promise((resolve, reject) => {
        setTimeout(()=>{
            let data='Database data'
            // resolve(data) 
            reject(data) 
        })
    })

p.then(function (value){   // If successful, execute the first callback function
    console.log(value)
},function (reason){      // If it fails, execute the second one
    console.error(reason)
})

Promise read file

//1. Introduce fs module
const fs = require('fs');
fs.readFile('./resource/content.txt',function(err,data){
    if(err)throw err;
    console.log(data); 
})


const p = new Promise(function(resolve,reject){
    require('fs').readFile('./resource/content.txt',function(err,data){
        if(err) reject(err);
        resolve(data);
    })
})
p.then(function(value){
    console.log(value.toString())
},function(reason){
    console.error('error Really successful');
})   

Promise encapsulates Ajax requests

//Interface address: https://api.apiopen.top/getJoke
const p = new Promise(function(resolve,reject){
    //1. Create object
    const xhr = new XMLHttpRequest();
    //2. Initialization
    xhr.open('GET', 'https://api.apiopen.top/geoke');
    //3. Send
    xhr.send();
    //4. Bind the event and process the response result
    xhr.onreadystatechange = function(){
        //judge
        if(xhr.readyState === 4)
        {
            //Judgment response status code 200-299
            if(xhr.status >= 200 && xhr.status < 300)
            {
                //Indicates success
                resolve(xhr.response);
            }
            else{
                //Indicates failure
                reject(xhr.status);
            }
        }
    }
})
p.then((value)=>{
    console.log(value);
},
(reason)=>{
    console.error(reason);
})

Promise.then() method

const p =new Promise((resolve, reject) =>{
    setTimeout(() => {
        resolve('user data') 
    })
});

//The actual returned by the then () function is also a Promise object
//1. When a non Promise attribute is returned after the callback, the status is fully. The return value of the then() function is the success value of the object, such as reutnr 123. The Promise object value returned is 123. If there is no return value, it is undefined

//2. When an object of Promise type is returned after the callback, the return value of the then() function is the state value of the Promise object

//3. After callback, if an exception is thrown, the return value status of the then () function is also rejected
let result = p.then(value => {
    console.log(value)
     //1. Properties of non Promise type
    // return 123 
     //2. Promise object
    // return new Promise((resolve, reject) => {
          // resolve('ok');
          // reject('error');// Rejected (failed)
    // })
    //3. Throw an error
    // throw new Error('error! ');
    // throw 'error!!!';
},reason => {
    console.log(reason)
})
console.log(result) 

Chain callback

p.then(value=>{}).then(value=>{})

Case Promise reads multiple files

//Introducing fs module
const fs = require('fs');
//Callback hell
// fs.readFile('./resource / grass. TXT', (err, data1) = >{
//     fs.readFile('./resource / untitled. TXT', (err, data2) = >{
//         fs.readFile('./resource / Title Wild Goose Pagoda. TXT', (err, data3) = >{
//             let result = `${data1} 
//             ${data2}  
//             ${data3} `;
//              console.log(result.toString());
//         })
//     })
// })
const p = new Promise((reslove,reject)=>{
    fs.readFile('./resource/grass.txt',(err,data)=>{
        reslove(data);
    })
})
p.then(value=>{
    return  new Promise((reslove,reject)=>{
        fs.readFile('./resource/Untitled.txt',(err,data)=>{
            reslove([value,data]);
        })
    })
}).then(value=>{
    return  new Promise((reslove,reject)=>{
        fs.readFile('./resource/Title Wild Goose Pagoda.txt',(err,data)=>{
            //Press in
            value.push(data);
            reslove(value);
        })
    })
}).then(value=>{
    console.log(value.join('\r\n'));
})

Promise.catch() method

const p = new Promise((resolve, reject) => {
    setTimeout(()=>{
        reject('Error ')
    },1000)
})

p.catch(reason => {
    console.log(reason)
})

12. Assemble

12.1 Set

ES6 provides a new data structure set. It is similar to an array, but the values of members are unique. The set implements the iterator interface, so you can use the "extension operator" and "for... Of..." to traverse

Properties and methods of the collection:

  • . size returns the number of elements in the collection
  • . add() adds a new element to return the current collection
  • . delete() deletes an element and returns a boolean value
  • . has() detects whether the collection contains an element and returns a boolean value
let s = new Set();
let s2 = new Set(['A','B','C','D'])

//Number of elements
console.log(s2.size) 

//Add new element E
s2.add('E') 

//Delete element A
s2.delete('A')

//Check for C
console.log(s2.has('C')) 

//empty
s2.clear()

console.log(s2) 

Application:

let arr = [1,2,3,4,5,4,3,2,1];
//1. Array de duplication
// let result = [...new Set(arr)];
// console.log(result);//[1, 2, 3, 4, 5]
//2. Intersection
let arr2 = [4,5,6,5,6];
let s2 = new Set(arr2);//4 5 6
// let result  = [...new Set(arr)].filter(item=>{
//     if(s2.has(item))
//     {
//         return true;
//     }
//     else{
//         return false;
//     }
// })
let result = [...new Set(arr)].filter(item=>s2.has(item))
console.log(result);//[4, 5]
//3. Union
let union = [...new Set([...arr,...arr2])];
console.log(union);//[1, 2, 3, 4, 5, 6]
//4. Difference set
let diff = [...new Set(arr)].filter(item=>!(s2.has(item)))
console.log(diff);// [1, 2, 3]

12.2 Map

ES6 provides a map data structure. It is similar to an object and is also a collection of key value pairs. However, the scope of "key" is not limited to strings. Various types of values (including objects) can be used as keys. Map also implements the iterator interface, so you can use the "extension operator" and "for... Of..." to traverse.

Properties and methods of Map:

  • . size get the number of key value pairs of Map (outermost layer)
  • . set(key,value) adds a key value pair
  • . delete(key) deletes the key value pair whose key is key
  • . get(key) gets the value whose key is key
  • for...of traverses every key value pair inside
let m = new Map();
//Add element
m.set('name','Li Ge Xiao');
m.set('lgx',function(){
    console.log('I can change the world');
})
let key = {
    school:'xianyi'
}
m.set(key,['Hangzhou','Chang'an','Faeries ']);

//size
console.log(m.size);

//Deleting a key value pair with the key name will return to the modified Map set
// m.delete(key);
m.delete('name');

//obtain
console.log(m.get('lgx'));
console.log(m.get(key));

//empty
// m.clear();

console.log(m);
//Traverse each key value pair inside
for(let v of m)
{
    console.log(v);
}

13. Class

ES6 provides a writing method closer to the traditional language, and introduces the concept of class as the template of the object. You can define a class by using the class keyword. Basically, the class of ES6 can be regarded as just a syntax sugar. ES5 can do most of its functions. The new class writing method only makes the writing method of object prototype clearer and more like the syntax of object-oriented programming.

//Constructor for ES5
function Phone(brand,price){
    this.brand = brand;
    this.price = price;
}    
Phone.prototype.call = function(){
    console.log('I can call');
}
//Instantiate object
let Huawei = new Phone('Huawei','2000');
console.log(Huawei);
Huawei.call();

//Constructor Class of ES6
class iPhone{
    //Constructor name cannot be modified
    constructor(brand,price){
        this.brand = brand;
        this.price = price;
    }
    //Methods must use this syntax, not the full object form of ES5
    call(){
        console.log('I can call');
    }
}
let onePlus = new iPhone("1+",1999);
onePlus.call();
console.log(onePlus);

Results:

13.1 static members

ES5 static member

function Phone(){} 
Phone.iname='mobile phone';//Static member, cannot be called by instantiated object
Phone.change= function(){
    console.log("I can change the world, but I have to change myself first");
}   
Phone.prototype.size = '5.5inch';
let nokia = new Phone();
console.log(Phone.iname);//mobile phone
Phone.change();//I can change the world, but I have to change myself first
console.log(nokia.iname);//undefined
console.log(nokia.size);//5.5inch

ES6 static member

class Phone{
    // Declare static member variables
    static name = 'mobile phone';
    static change(){
        console.log("I can change the world, but I have to change myself first");
    }
}
let nokia = new Phone();
console.log(nokia.name);//undefined
console.log(Phone.name);//mobile phone

13.2 constructor inheritance

function Phone(brand,price){
    this.brand = brand;
    this.price = price;
}
Phone.prototype.call = function(){
    console.log("I can call");
}
function SmartPhone(brand,price,color,size)
{
    Phone.call(this,brand,price);
    this.color = color;
    this.size = size;
}
SmartPhone.prototype = new Phone();
//If you modify the prototype object in the form of an object, don't forget to use the constructor to refer back to the original prototype object
SmartPhone.constructor = SmartPhone;
SmartPhone.prototype.photo = function(){
    console.log('I can take pictures');
}
SmartPhone.prototype.playGame = function(){
    console.log('I can play games');
}

let chuizi = new SmartPhone('chuizi',2499,'black','5.5inch');
console.log(chuizi);

result:

13.3 Class inheritance

class Phone{
    constructor(brand,price){
        this.brand = brand;
        this.price = price;
    }
    call(){
        console.log("I can call");
    }
}
class SmartPhone extends Phone{
    constructor(brand,price,color,size){
        super(brand,price);//Phone.call(this,brand,price)
        this.color = color;
        this.size = size;
    }
    photo(){
        console.log('I can take pictures');
    }
    playGame(){
        console.log('I can play games');
    }
}
let xiaomi = new SmartPhone('millet',1999,'black','4.7inch');
console.log(xiaomi);
xiaomi.call();
xiaomi.photo();
xiaomi.playGame();

result:

13.4 override of subclass to parent method

class Phone{
    constructor(brand,price){
        this.brand = brand;
        this.price = price;
    }
    call(){
        console.log("I can call");
    }
}
class SmartPhone extends Phone{
    constructor(brand,price,color,size){
        super(brand,price);//Phone.call(this,brand,price)
        this.color = color;
        this.size = size;
    }
    photo(){
        console.log('I can take pictures');
    }
    playGame(){
        console.log('I can play games');
    }
    //rewrite!!!
    call(){
        console.log('I can make video calls');
    }
}
let xiaomi = new SmartPhone('millet',1999,'black','4.7inch');
console.log(xiaomi);
xiaomi.call();
xiaomi.photo();
xiaomi.playGame();

Results:

13.5 get and set settings

class Phone{
    get price(){
        console.log('The price attribute has been read');
        return '10000yuan';
    }
    set price(newVal){
        console.log('The price attribute has been modified');
    }
}
//Instantiate object
let s = new Phone();
console.log(s.price);//10000yuan
s.price = "free";

Results:

14 numerical extension

// Number.EPSILON is the minimum precision of JavaScript, and the value of the attribute is close to 2.22044 E-16
function equal(a,b){
    if(Math.abs(a-b)<Number.EPSILON)
    {
        return true;
    }
    else{
        return false;
    }
}
console.log(0.1+0.2===0.3);//false
console.log(equal(0.1+0.2,0.3));//true

//1. Binary and octal
let b = 0b1010;//10 / / binary
let o = 0o777;//511 / / octal
let d = 100   //100 / / decimal
let x = 0xff  //255 / / hex
console.log(x);

//2. Check whether a number is finite
console.log(Number.isFinite(100));//true
console.log(Number.isFinite(100/0));//false
console.log(Number.isFinite(Infinity));//false

//3. Check whether a value is NaN
console.log(Number.isNaN(123));//false

//4. String to integer
console.log(Number.parseInt('5454545love'));//5454545
console.log(Number.parseFloat('5.123123 magical'));//5.123123

//5. Judge whether it is an integer
console.log(Number.isInteger(5));//true
console.log(Number.isInteger(2.5));//false

//6. Erase the decimal part
console.log(Math.trunc(3.5));//3

//7. Check whether a number is positive, negative or 0
console.log(Math.sign(100));//1
console.log(Math.sign(0));//0
console.log(Math.sign(-20000));//-1

result:

 

15. Object method extension

//1.Object.is determines whether the two values are exactly equal
console.log(Object.is(120,120));//===  //true
console.log(Object.is(isNaN,isNaN));//===  //true
console.log(NaN===NaN);//false

//2.Object. Merge of assign objects
const config1={
host:'localhost',
port:'3306',
name:'root',
pass:'root',
test:'test'
}
const config2={
host:'http://xianyi.com',
port:'33060',
name:'xianyi.com',
pass:'lixiaoyao',
}
console.log(Object.assign(config1,config2));//{host: 'http://xianyi.com', port: '33060', name: 'xianyi.com', pass: 'lixiaoyao', test: 'test'}

//3.Object.setPrototypeOf sets the prototype object getPrototypeof
const school = {
name:'Li Ge Xiao'
}
const cities = {
renming:['Li Xiaoyao','Zhao linger','Lin Yueru']
}
Object.setPrototypeOf(school,cities);
console.log(Object.getPrototypeOf(school));//{renming: Array(3)}
console.log(school);//{name: 'leaving song laughing'}

16. Modularization

Modularization refers to splitting a large program file into many small files, and then combining the small files.

1. Benefits of modularity:

  • Prevent naming conflicts
  • code reuse
  • High maintainability
  • Modular standardized products

6. Previous modular ES2:

  • CommonJS ====> NodeJS,Browserify
  • AMD ====> requireJS
  • CMD ====> seaJS

3. Syntax:

  • The module function is mainly composed of two commands: export and import
  • The export command is used to specify the external interface of the module
  • The import command is used to input functions provided by other modules

16.1 exposure syntax

16.1.1. Separate exposure

// The following JS code is placed in/ js/m1.js file
//Separate exposure
export let school = 'Li Ge Xiao';
export function teach(){
    console.log('A song of parting laughs at the Jianghu');
}
<!-- html code -->
<script type="module">
//Introduce modular content
import * as m1 from "./js/m1.js";
console.log(m1);
</script>

Results:

16.1.2. Unified exposure

let school = 'Tsinghua University';
function findjob(){
    console.log('Look for a job');
}
//Unified exposure
export {school, findjob}
<script type="module">  
    import * as m1 from "./js/m1.js" 
    console.log(m1) 
    console.log(m1.school)
    m1.findJob()
</script>

result:

 16.1.3. Default exposure (multivariable exposure)

//Default export default
export default {
    school:'Tsinghua University',
    change:function(){
        console.log('Can change one's life!')
    }
}
<script type="module">  
        import * as m1 from "./js/m1.js" 
        console.log(m1.default) 
        console.log(m1.default.school)
        console.log(m1.default.change())
</script>

result:

16.2 introduction of grammar

16.2.1. General import method

import * as m1 from "./js/m1.js"
import * as m2 from "./js/m2.js"
import * as m3 from "./js/m3.js"

 16.2.2. Deconstruction assignment method

import {school,teach} from "./js/m1.js";
import {school as s ,findJob} from "./js/m2.js";
import {default as m3} from "./js/m3.js";
console.log(school,teach);
console.log(s,findJob);
console.log(m3);

result:

 16.2.3. Simple form (for default exposure only)

import m3 from "./js/m3.js";
console.log(m3);//{school: 'Tsinghua University', change: ƒ}

16.3 modular mode 2

// The following JS code is placed in/ js/app.js file
//Entry file

//Module introduction
import * as m1 from "./m1.js";
import * as m2 from "./m2.js";
import * as m3 from "./m3.js";

console.log(m1);
console.log(m2);
console.log(m3);
<!-- html code -->
<script type="module" src="./js/app.js"></script>

Results:

16.4 bael to es6 modular code conversion

Babel summary:
Babel It's a JavaScript compiler;
Babel can convert the new ES specification syntax into ES5 syntax;
Because not all browsers support the latest ES Specification, so it needs to be used in general projects Babel Convert;
Step: use Babel transformation JS code - Package into one file - It can be introduced when in use;

step

Step 1: install the tool Babel cli (command line tool) Babel preset env (ES conversion tool) browserify (packaging tool, webpack is used in the project);

Step 2: initialize the project

npm init -y
Step 3: installation
npm i babel-cli babel-preset-env browserify -D
Step 4: use babel transformation
npx babel js (js directory) - d dist/js (converted js directory) -- presets = Babel preset env
Step 5: package
npx browserify dist/js/app.js -o dist/bundle.js
Step 6: introduce bundle.js
< script src = "./js/bundle.js" type = "module" >< /script>
Comparison before and after conversion:
Before conversion:
//Separate exposure
export let school = 'Li Ge Xiao';
export function teach(){
    console.log('A song of parting laughs at the Jianghu');
}
After conversion:
'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.teach = teach;
//Separate exposure
var school = exports.school = 'Li Ge Xiao';
function teach() {
    console.log('A song of parting laughs at the Jianghu');
}

16.5 ES6 modular introduction of NPM package

Step 1: install jquery:

npm i jquery

Step 2: on app JS using jquery

//Change the background color to pink
import $ from 'jquery';//const $ = require("jquery");
$('body').css("background","pink");

Step 3: re convert and package

npx babel js (js directory) - d dist/js (converted js directory) -- presets = Babel preset env

npx browserify dist/js/app.js -o dist/bundle.js

2, New features of ES6

1,Array.prototype.includes

summary:
Includes Method is used to detect whether an element is contained in the array and return a Boolean value;
To judge whether the array contains an element, the syntax is: arr.includes( Element value ) ;
const renming = ['Li Xiaoyao','Zhao linger','Lin Yueru','Liu Jinyuan'];
console.log(renming.includes('Li Xiaoyao'));//true
console.log(renming.includes('Li Ge Xiao'));//false

2. Exponential operator

summary:
stay ES7 Exponential operator ** ", used to realize power operation, function and Math.pow The results are the same;
Simplified expression of power operation, for example: 2 of 10 Power: 2**10 ;
//**(exponential operator)
console.log(2**10);//1024
console.log(Math.pow(2,10));//1024

3, New features of ES8

1. async and await

summary:
async and await The combination of the two syntax can make asynchronous code look like synchronous code;
Simplify the writing of asynchronous functions;

3.1.1 sync function

summary:
1. async The return value of the function is promise Object;
2. promise The result of the object is determined by async The return value of function execution is determined;

1. The returned result is not an object of Promise type, and the returned result is a successful Promise object

2. Throw an error, and the returned result is a failed Promise

3. If the returned result is a Promise object, success is success and failure is failure

// async function
async function fn(){
    //Returns a string
    // return 'Li Ge laughs'// fulfilled
    //The returned result is not an object of Promise type. The returned result is a successful Promise object
    // return; 
    //An error is thrown, and the returned result is a failed Promise
    // throw new Error('error! ');
    //If the returned result is a Promise object
    return new Promise((resolve,reject)=>{
        resolve('Successful data');//fulfilled
        //   reject('failed data ')// rejected
    })
}    
const result = fn();
// console.log(result);
//Call the then method
result.then(value=>{
    console.log(value);
},(reason)=>{
    console.warn(reason);
})

3.1.2 wait expression

summary:
1. await Must be written in async In function;
2. await The expression on the right is generally promise Object;
3. await Return is promise Value of success;
4. await of promise failed , Will throw an exception , Need to pass try...catch Capture processing;
//Create Promise object
const p = new Promise((resolve,reject)=>{
    // resolve('succeeded ');
    reject('The reasons for the failure are complex');
})    

//await is placed in the async function
async function main(){
    try{
        const result = await p;
        console.log(result);
    }
    catch(e){
        console.log(e);//The reasons for the failure are complex
    }
}
//Call function
main();

3.1.3async and await read files

const fs = require('fs');
function readCao(){
    return new Promise((reslove,reject)=>{
        fs.readFile('./resource/grass.txt',(err,data)=>{
            if(err){reject(err);}
            reslove(data);
        })
    })
}
function readWuTi(){
    return new Promise((reslove,reject)=>{
        fs.readFile('./resource/Untitled.txt',(err,data)=>{
            if(err){reject(err);}
            reslove(data);
        })
    })
}
function readTiYanTa(){
    return new Promise((reslove,reject)=>{
        fs.readFile('./resource/Title Wild Goose Pagoda.txt',(err,data)=>{
            if(err){reject(err);}
            reslove(data);
        })
    })
}

async function main(){
    //Article 1
    try{
        let cao = await readCao();
        console.log(cao.toString());
    }
    catch(e){
        console.log(e);
    }
    //Article 2
    try{
        let wuti = await readWuTi();
        console.log(wuti.toString());
    }
    catch(e){
        console.log(e);
    }
    //Article 3
    try{
        let tiyanta = await readTiYanTa();
        console.log(tiyanta.toString());
    }
    catch(e){
        console.log(e);
    }
}
main();

result:

3.1.4 send ajax request with async and await

//Send an Ajax request, and the result returned is a Pomise object
function sendAJAX(url) {
    return new Promise((resolve,reject)=>{
        //1. Create object
        const xhr = new XMLHttpRequest();
        //2. Initialization
        xhr.open('GET',url);
        //3. Send
        xhr.send();
        //4. Event binding
        xhr.onreadystatechange = ()=>{
            if(xhr.readyState === 4)
            {
                if(xhr.status>=200 && xhr.status<300)
                {
                    //success
                    resolve(xhr.response);
                }
                else{
                    //fail
                    reject(xhr.status);
                }
            }
        }
    })
}

//Promise then method test
// sendAJAX('https://api.apiopen.top/getJoke').then((value)=>{
//     console.log(value);
// },(reason)=>{
//     console.log(reason);
// })

//Using async and await
async function main(){
    //Send AJAX request
    let result =  await sendAJAX('https://api.apiopen.top/getJoke');
    console.log(result);
}
main();

2. Object method extension

Object.values,Object.entries and

Object.getOwnPropertyDescriptors:

1. Object.values() Method: returns the name of a given object All enumerable attribute values Array of;
2. Object.entries() Method: returns the traversable property of a given object itself [key,value] Array of; (object becomes array)
3. Object.getOwnPropertyDescriptors() This method: returns the description object of all its own attributes of the specified object;
//Declaration object
const school = {
    name:'Li Ge Xiao',
    cities:['Hangzhou','Chang'an','Bianliang'],
    zhiye:['daxia','taifu','gongzhu']
}    

//Get all keys of the object
console.log(Object.keys(school));//['name', 'cities', 'zhiye']
//Gets all the values of the object
console.log(Object.values(school));//['Li Ge Xiao', Array(3), Array(3)]0: "Li Ge Xiao" 1: (3) [Hangzhou ',' Chang'an ',' Bianliang '] 2: (3) [daxia', 'taifu', 'gongzhu']length: 3[[Prototype]]: Array(0)
//entries
console.log(Object.entries(school));//[Array(2), Array(2), Array(2)]
//Create Map
const m = new Map(Object.entries(school));
console.log(m.get('cities'));//['Hangzhou', 'Chang'an', 'Bianliang']

//Description of object properties
console.log(Object.getOwnPropertyDescriptors(school));//{name: {...}, cities: {...}, zhiye: {...}}

const obj = Object.create(null,{
    name:{
        //Set value
        value:'Li Ge Xiao',
        writable:true,//Whether the value can be overridden. true|false the default is false
        configurable:true,//Whether the target attribute can be deleted or the feature can be modified again. true|false is false by default
        enumerable:true,//Whether the target attribute can be enumerated. true|false the default is false
    }
})

result:

5, New features of ES9

1. Rest parameter and spread extension operator

summary:
Rest Parameters and spread Extension operator in ES6 Has been introduced in, but ES6 For arrays only, in ES9 in
Provides for objects Like an array rest Parameters and extension operators;
// Rest parameter and spread extension operator 
// Rest parameter and spread extension operator have been introduced in ES6,
// However, only for arrays in ES6, images are provided for objects in ES9 
// Array like rest parameters and extension operators    
function connect({name,age,...user}){
    console.log(name);
    console.log(age);
    console.log(user);
}

connect({
    name:'Li Ge Xiao',
    age:20,
    price:5000,
    wuli:10000000
})
const skillOne = {
    x:'Immortal wind and cloud body technique'
}
const skillTwo = {
    z:'Drunken fairy looking at the moon step',
    a:'Infinite love'
}
const skillThree = {
    q:'Seven Jue sword Qi'
}
const skillFour = {
    y:'Sword Art'
}

const lixiaoyao = {...skillOne,...skillTwo,...skillThree,...skillFour};//Merge of objects
console.log(lixiaoyao);//{x: 'immortal wind and cloud body skill', z: 'drunken immortal looking at the moon step', q: 'seven Jue sword Qi', y: 'sword defense'}

result:


2. Regular extension: named capture group

summary:
ES9 Allow named capture groups to use symbols ? 』 , In this way, the readability of the capture results is stronger;
//Declare a string
let str = '<a href="http://baidu. Com "> Li Ge Xiao < / a > ';

//Extract url and [label text]
const reg = /<a href="(.*)">(.*)<\/a>/

//implement
const result = reg.exec(str);
console.log(result[1]);//http://baidu.com
console.log(result[2]);//Li Ge Xiao

let str1 = '<a href="http://baidu. Com "> Li Ge Xiao < / a > ';
const reg1 = /<a href="(?<url>.*)">(?<text>.*)<\/a>/;
const result1 = reg.exec(str1); 
// console.log(result1);
console.log(result1.groups.url);//http://baidu.com
console.log(result1.groups.text);//Li Ge Xiao

3. Regular extension: reverse assertion

summary:
ES9 Support reverse assertion, and filter the matches by judging the contents in front of the matching results;
//Declaration string
let str = 'JS5201314 You know, 555 Lala';
//Forward assertion
const reg = /\d+(?=la)/;
const result = reg.exec(str);

//Reverse assertion
const reg1 = /(?<=Do you)\d+/;
const result1 = reg1.exec(str);
console.log(result1);

4. Regular extension: dotAll mode

summary:
Regular expression midpoint . Match any single character except carriage return, mark 「 s "Change this behavior and allow line terminators to appear;

//dot .  A single character other than a newline character
let str = `
    <ul>
        <li>
            <a>the shawshank redemption </a>
            <p>Release date: 1994-09-10</p>
        </li>
        <li>
            <a>Forrest Gump</a>
            <p>Release date: 1994-07-06</p>
        </li>
    </ul>
`;

//Declarative regularity
// const reg = /<li>\s+<a>(.*?)<\/a>\s+<p>(.*?)<\/p/;
const reg = /<li>.*?<a>(.*?)<\/a>.*?<p>(.*?)<\/p>/gs;
//Perform matching
// const result = reg.exec(str);
let result;
let data =[];
while(result = reg.exec(str)){
    data.push({title:result[1],time:result[2]});
}
//Output results
console.log(data);

result:

Vi. new features of ES10

1,Object.fromEntries

summary:
A two-dimensional array or map Convert to object;
Learned before Object.entries Is to convert an object into a two-dimensional array;
// Object.fromEntries: converts a two-dimensional array or map into an object 
// Previously learned object Entries is to convert an object into a two-dimensional array 
// This method receives a two-dimensional array or a map collection 
// Two dimensional array
const result = Object.fromEntries([
['name','Li Ge Xiao'],
['city','Chang'an,Yu Hang,Faeries ']
]);
console.log(result);//{name: 'Li Ge Xiao', city: 'Chang'an, Yuhang, Xianling'}
//Map
const m = new Map();
m.set('name','ligexiao')
console.log(m);//Map(1) {'name' => 'ligexiao'}
const result1 = Object.fromEntries(m);
console.log(result1.name);//ligexiao
console.log(result1);//{name: 'ligexiao'}
//Object.entries ES8
const arr = Object.entries({
name:'Moegi '
});
console.log(arr);

Results:

2. trimStart and trimEnd

summary:
Remove the blank characters before and after the string;
//trim
let str = '   ligexiao   ';
console.log(str);//   ligexiao   
console.log(str.trim());//ligexiao
console.log(str.trimStart());//ligexiao   
console.log(str.trimEnd());//   ligexiao

Results:

3,Array.prototype.flat and flatMap

summary:
Convert multi-dimensional array into low-dimensional array;
//Flat flat
//Convert multidimensional array to low dimensional array
// const arr = [1,2,3,[4,5,6]];// [1, 2, 3, 4, 5, 6]
// const arr = [1,2,3,4,[5,6,7,[8,9,0]]];// [1, 2, 3, 4, 5, 6, 7, Array(3)]    Array(3):[8, 9, 0]
const arr = [1,2,3,4,[5,6,7,[8,9,0]]];
//The parameter is depth, which is a number
console.log(arr.flat(2));// [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

//flatMap converts the multi-dimensional array obtained from the map into a low-dimensional array
const arr1 = [1,2,3,4];
const result0 = arr1.map(item=>item * 10);//[10, 20, 30, 40]
const result1 = arr1.map(item=>[item*10]);//Array(1), Array(1), Array(1), Array(1)] -> [10][20][30][40]
const result2 = arr1.flatMap(item=>item * 10);//[10, 20, 30, 40]
console.log(result0);
console.log(result1);
console.log(result2);

Results:

4,Symbol.prototype.description

summary:
obtain Symbol Description string of;
//Create Symbol
let s = Symbol('Li Ge Xiao');
console.log(s.description);//Li Ge Xiao

7, New features of ES11

1,String.prototype.matchAll

summary:
Used to get the results of regular batch matching;
let str = `
    <ul>
        <li>
            <a>the shawshank redemption </a>
            <p>Release date: 1994-09-10</p>
        </li>
        <li>
            <a>Forrest Gump</a>
            <p>Release date: 1994-07-06</p>
        </li>
    </ul>
`;
//Declarative regularity
const reg = /<li>.*?<a>(.*?)<\/a>.*?<p>(.*?)<\/p>/sg
//Method call
const result = str.matchAll(reg);
for(let v of result)
{
    console.log(v);
}
// const arr = [...result];
// console.log(arr);

Results:

2. Private properties of class

summary:
Private attributes cannot be accessed directly from outside; (can be used internally, not externally)
class Person{
    //Public attribute
    name;
    //Private property
    #age;
    #weight;
    //Construction method
    constructor(name,age,weight){
        this.name = name;
        this.#age = age;
        this.#weight = weight;
    }
    intro(){
        console.log(this.name);
        console.log(this.#age);
        console.log(this.#weight);
    }
}

const girl = new Person('Liu Yifei','18','40kg');
console.log(girl);
console.log(girl.name);
console.log(girl.#age);
console.log(girl.#weight);
girl.intro();

 

3,Promise.allSettled

summary:
Get multiple promise Result set of execution;
//Declare two Promise objects
const p1 = new Promise((resolve,reject)=>{
    setTimeout(()=>{
        resolve('Commodity data -1');
    },1000)
})
const p2 = new Promise((resolve,reject)=>{
    setTimeout(()=>{
        resolve('Commodity data -2');
        // reject("something went wrong");
    },1000)
})
//Call the allSettled method
const result = Promise.allSettled([p1,p2]);
console.log(result);
const res = Promise.all([p1,p2]);//Both are success, and one failure is failure
console.log(res);

Results:

Call the allSettled method

Call all method

4. Optional chain operator

summary:
?.
If it exists, go down and omit the layer by layer judgment of whether the object is passed in;
//?.
function main(config)
{
    const dbHost = config && config.db && config.db.host;
    console.log(dbHost);//192.168.0.1
    const cacheHost = config?.cache?.host;
    console.log(cacheHost);//192.168.0.2
}
main({
    db:{
        host:'192.168.0.1',
        username:'root'
    },
    cache:{
        host:'192.168.0.2',
        username:'admin',
    }
})

5. Dynamic import

Overview:

Dynamic import module, when to use and import;

html page:

<script type="module" src="./js/app1.js"></script>
<button id="btn">welcome to beijing</button>

app.js:

//Static import
import * as m1 from './hello.js';
const btn = document.getElementById('btn');
btn.onclick = function(){
    // m1.hello2();
    //Dynamic import
    import('./hello.js').then(module=>{
        module.hello();
    })
}

hello.js:

export function hello(){
    alert('Beibei Jingjing greets Nini with joy');
}
export function hello2(){
    alert('Beibei Jingjing welcomes Nini 2');
}

6,BigInt

summary:
Larger integer;
//Large plastic surgery
let n = 521n;
console.log(n,typeof(n));//521n 'bigint'

//Function: General shaping to large shaping
let x = 123;
console.log(BigInt(n));//521n
// console.log(BigInt(1.2)); // Error, bigint cannot be calculated with floating point number

//For operations with larger values
let max = Number.MAX_SAFE_INTEGER;
console.log(max);//9007199254740991
console.log(max+1);//9007199254740992
console.log(max+2);//9007199254740992 error max+1 is the maximum calculation

console.log(BigInt(max));//9007199254740991n
console.log(BigInt(max)+BigInt(1));//9007199254740992n
console.log(BigInt(max)+BigInt(2));//9007199254740993n

Results:

 

7. globalThis object

summary:
Always point to global objects window ;
console.log(globalThis);

Results:

Topics: Javascript Front-end Vue.js