A common API for ES6

Time:2021-9-18

preface

This article mainly records the common syntax API of ES6 to achieve the purpose of quick reference. It is not suitable for novices to learn. Now the new version of Chrome browser has fully supported ES6 syntax. When testing and learning ES6 syntax, you can directly use Google browser without considering the troublesome Babel conversion[Note: online code must be used]

Let variable

1. Declare variable

let a;
let b,c,d;
let e = 100;

2. Let variable declaration cannot be repeated, but var declaration is allowed

Let name = 'Wukong';
Let name = 'Wukong'; //报错

3. Let only takes effect within the scope of block level. An error is reported when accessing let variables outside the scope, but var declaration is allowed

if else while for 
 {
     Let Name2 = 'eight commandments';
 }
 console.log(name2); // report errors

4. There is no variable promotion, but var declaration is allowed

console.log(name3);
Let name3 = 'Tang Monk'// An error is reported. Name3 must be defined before accessing

5. Scope chain

{
    Let name4 = 'monk Sha';
    function fn(){
        console.log(name4); // You can access data from the perimeter scope
    }
    fn();
}

6. Using let to define loop variables in loop statements

<body>
    <ul>
        <li>Elder martial brother, Shifu was captured by a monster</ li>
        <li>Eldest martial brother, Shifu and second martial brother were captured by monsters</ li>
        <li>Second senior brother, Shifu was captured by a monster</ li>
    </ul>
    <script>
        //Get div element object
        let items = document.getElementsByTagName('li');
        //Traverse and bind events. If it is changed to var variable definition, an error will be reported
        for(let i = 0;i<items.length;i++){
            items[i].onclick = function(){                
                items[i].style.background = 'pink'; // Modify the background color of the current element
            }
        }        
    </script>
</body>

Const variable

1. Be sure to assign an initial value, otherwise an error will be reported

const NAME;  //Uncaught SyntaxError: Missing initializer in const declaration

2. Constants are capitalized (default)

const NAME2 = 100;

3. The value of a constant cannot be modified

Const name3 = 'ox demon king';
Const name3 = 'Iron Fan Princess'// Uncaught SyntaxError: Identifier 'NAME3' has already been declared

4. Block level scope, invalid outside scope

 {
     const NAME4 = '';
 }
console.log(NAME4);    //test.html:41 Uncaught ReferenceError: NAME4 is not defined

5. For the element modification of arrays and objects, it does not count as the modification of constants, and no error will be reported

Const name5 = ['Baigujing', 'Honghe'];
Name5. Push ('leopard demon ')// success

Template string

Template string action andpreLike tags, it is an enhanced version of it. You can write JS string code format at will in the code, and supports variable splicing.

1. Write special format JS string

let xyj = `
    Elder martial brother, Shifu was captured by a monster,
    Eldest martial brother, Shifu and second martial brother were captured by monsters
    Second senior brother, Shifu was captured by a monster
 `    
 console.log(xyj);

2. Variable splicing use${variable name}

Let name1 = 'senior brother, master';
 Let Name2 = 'senior brother, master and second senior brother';
 Let name3 = 'Second Senior brother, master';
 let xyj = `
    ${name1} was caught by a monster,
    ${Name2} was caught by a monster
    ${name3} was caught by a monster
 `    
 console.log(xyj);

Destructuring assignment

Deconstruction can easily obtain the defined data from the array and object according to the storage structure order of the array and object.

1. Get data from array

Let XYJ = ['Wukong', 'Bajie', 'Shaseng', 'Tangseng'];
let [wukong, bajie, shasen, tangseng] = xyj;
console.log(wukong);
console.log(bajie);
console.log(shasen);
console.log(tangseng);

2. Get data from object

let xyj = {
   Wukong: 'Wukong',
   Bajie: 'Eight Precepts',
   other:{
     Shaseng: 'monk Sha'
   }
 };
 
 let {wukong, bajie, other} = xyj;
 console.log(wukong);        
 console.log(bajie);        
 console.log(other.shaseng);

Arrow function

1. ES6 use=>The format defines the arrow function, such as the following format:

let func1 = () => {
     Console. Log ('I believe you can find your own Superman without this Counsellor ');
 }        
 func1();

2. Cannot instantiate an object as a construct

let Func2 = () => {
     Val: 'everyone has a stroke in his heart. He puts the bad things he has committed and the punishment he should be punished at the same time.'       
 }
        
 let f = new Func2('xiao',30); //Uncaught SyntaxError: Unexpected identifier

3. Noargumentsvariable

 let Func3 = () => {
     console.log(arguments);     
 }        

 Func3() //test.html:39 Uncaught ReferenceError: arguments is not defined

4. Abbreviated form of arrow function

//When there is only one formal parameter, parentheses can be omitted
 let Func4 = val => {
     console.log(val);     
 }    
 Func4 ('fu Seoul classic sentence inventory ')
 
 //When there is only one statement in contemporary code body, curly braces and return can be omitted
 let sum = n => n + n;
 console.log(sum(1));

5. The arrow function does not changethispoint
The arrow function does not change the point of this. It is suitable for specifying callback functions, such as timer, JS array and related methods.
The arrow function is not suitable for callbacks related to this, such as methods of objects.

//Array callback function
const arr = [1,20,100,25];
const result = arr.filter(val => val % 2 === 0);
console.log(result);

Remaining parameters

The remaining parameters consist of three points(...)Specified with a named parameter immediately following it to obtain the argument of the function instead ofarguments

function fn(a,b,...args){
    console.log(a); // Zeng Xiaoxian
    console.log(b); // Hu Yifei
    console.log(args);    // ["Lv ziqiao", "Chen Meijia", "Zhang Wei"]        
 }
 FN ('zeng Xiaoxian ',' Hu Yifei ',' LV ziqiao ',' Chen Meijia ',' Zhang Wei ');

Note:
1. The remaining parameters must be placed last
2. The remaining parameters are real arrays, and arguments are class array structures

Extension operator

The remaining parameters allow you to combine multiple independent parameters into an array; The extension operator allows you to split an array and pass each item to the function as a separate parameter.

function fn(a,b,c){
    console.log(a); // Zeng Xiaoxian
    console.log(b); // Hu Yifei
    console.log(c); // LV ziqiao        
 }
 Let arr = ['Zeng Xiaoxian', 'Hu Yifei', 'LV ziqiao'];
 fn(...arr);

In addition to splitting the items in the array, the extension operator can be used as the separation parameter of the function. You can also use extension operators on iteratable objects (such as set) to convert them into arrays.

let set = new Set([1,2,3,3,3,4,5]);                
let array = [...set];
console.log(array); //[1, 2, 3, 4, 5]

Numerical extension

1、Number.EPSILON
Number.EPSILONIs the minimum precision represented by JS. When JS performs decimal operation, the result will be inaccurate and can be usedNumber.EPSILONFor reference.

//Method of comparing floating point numbers in JS
function equal(a, b){
     if(Math.abs(a-b) < Number.EPSILON){
         return true;
     }else{
         return false;
     }
}
console.log(0.1 + 0.2 === 0.3);
console.log(equal(0.1 + 0.2, 0.3));

2、Number.isNaN
Check whether a value isNaN

console.log(Number.isNaN(11111));

3、Number.isInteger
Judge whether a number is an integer

console.log(Number.isInteger(2.5));

4、Number.isFinite
Check whether a value is finite

console.log(Number.isFinite(100/0));
console.log(Number.isFinite(Infinity));

5、Number.parseInT andNumber.parseFloat
String to integer and string to floating point, and remove the part that cannot be converted

console.log(Number.parseInt('32324sdf'));
console.log(Number.parseFloat('3.1415sdfsd'));

Object method extension

1、Object.is
Object.isJudge whether the two values are exactly equal, almost equal to===Equivalent.

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

var aa = {};
var bb = {};
console.log(aa === bb); //false
console.log(Object.is(aa === bb)); //false

2、Object.assign
Object.assignFor merging objects, copy all enumerable properties of one or more source objects to the target object.

let rec = {};
const conf = {
    Target: 'get scriptures',
    Person: ['Tang Monk', 'Wukong']
}

//The attribute whose enumerable is false will not be copied
Object.defineProperty(conf, 'height' ,{
    value: '188',
    enumerable: false
})    

Object.assign(rec,conf);    
console.log(rec); // {target: "get scriptures", person: array (2)}

//The reference type copies pointers, which will modify the person attribute data of the conf object
Rec.person.push ('eight precepts');
console.log(conf); // {target: "get scriptures", person: array (3), height: "188"}

3. Simplified object attribute writing
When the attribute name and attribute value of an object have the same name, the colon and attribute value can be omitted; Functions can be omitted:andfunctionkeyword.

Let name = 'Wukong';
 let age = 19;
 let person = {
    name,
    age
 }
 console.log(person);

symbol

Existing basic types in JS(character stringnumerical valueBoolean typenullAndundefined)Outside (abbreviation)UOSNB), ES6 introduces a new basic type: symbols(Symbol

1. Create symbol

//Create symbol
let symbol = Symbol(); 

//Create symbol,并且带有描述
let symbolDes =  Symbol('desctription'); 
let symbolDes2 = Symbol('desctription');

//Although there are other methods to judge whether a variable is of symbol type, the typeof operator is still the most accurate and preferred means
console.log(typeof symbol);  

//Even if the descriptions of strings created by symbol ('description string ') are the same, the comparison results are different
console.log(symbolDes === symbolDes2);  //false

//Another way to create symbols is to be globally unique and stored in the global symbol registry for sharing
let uid =  Symbol.for('uid'); 
let uid2 = Symbol.for('uid'); 

//The symbol. For () method is globally unique, so the comparison results are equal
console.log(uid === uid2); //true

//Add symbol type to object
let uid =  Symbol.for('uid');
var friend = {
    [uid]:123,
    Name: 'brother pony',
    age:18
};

//For other matters, symbol type variables cannot be operated with other types of variables such as strings

2. Global symbol registry
The global symbol registry is similar to the global scope. It is a shared environment. The symbol variable created by symbol. For () is stored in the global symbol registry. This means that we are not sure if some values already exist. When using third-party components, using namespaces for the key values of symbols can reduce the possibility of naming conflicts. For example, query code should use the prefix of “jQuery.” for all its key values, such as “jQuery. Element” or similar form.

3、SymbolBuilt in properties
The prototype object contains some built-in properties that can be manipulated by manipulating the objectSymbol PropertiesModify the native default behavior. For example:

class MyNumber {        
}

Object.defineProperty(MyNumber, Symbol.hasInstance,{
    value:function(val){
        Console.log ('This function has been transferred... ');
        return (val instanceof Number) && (val>=1 && val<=100)
    }
})

let a = new Number(-1);
let b = new Number(2);

//Every time instanceof is called, the symbol.hasinstance function defined above will be triggered
console.log( a instanceof MyNumber);
console.log( b instanceof MyNumber);
console.log( b instanceof MyNumber);
console.log( b instanceof MyNumber);
//-----------Operation results------------
//This function is called...
//test.html:53 false
//Test. HTML: 45 this function has been called...
//test.html:54 true
//Test. HTML: 45 this function has been called...
//test.html:55 true
//Test. HTML: 45 this function has been called...
//test.html:56 true

The above results can explain:We redefined the objectSymbol.hasInstanceProperty whenever we useinstanceofOperator will be triggeredSymbol.hasInstanceProperty, and whether an object is an instance of a constructor is completely determined by our custom rules.

iterator

1. Symbol.iterator property

Let’s first look at the new iteration of arrays.

Const Xiyouji = ['monk Tang', 'Monkey King', 'pig Bajie', 'monk Sha'];
    
for(let name of xiyouji){
    console.log(name);
}

Why can arrays be usedfor...of...How to cycle through? Because the array object prototype containsSymbol.iteratorProperties. Next, let’s take a look at the above dataSymbol.iteratorWhat are attributes.

console.log(xiyouji[Symbol.iterator]);  // The result is: ƒ values() {[native code]}, which is a function

//Call the function and print the result
let iterator =  xiyouji[Symbol.iterator]();
console.log(iterator.next()); // {value: "Tang Monk", done: false}
console.log(iterator.next()); // {value: "Monkey King", done: false}
console.log(iterator.next()); // {value: "pig Bajie", done: false}
console.log(iterator.next()); // {value: "monk Sha", done: false}
console.log(iterator.next()); //{value: undefined, done: true}

Conclusion:
Symbol.iteratorSymbols are used to define the default iterators for objects. Both built-in objects and developer defined objects can use this symbol to provide a method that can return iterators. WhenSymbol.iteratorWhen an object exists, it is considered an iteratable object.

for-ofLoop uses iteratable objects in the loop to return a series of data. Compared with iterating with a traditional for loop, usingfor-ofIt’s much easier because you no longer need to track the counter and control when the loop ends.for-ofThe loop automatically reads all data from the iterator until there is no more data, and then exits the loop.

2. Custom iterator

We refer to the iterative method of the above array to add custom objectsSymbol.iteratorProperty, implemented withfor...of...Mode loop traversal(think of iterators when you need to customize the traversal data)

const AiQing = {
        name:[
            'Zeng Xiaoxian',
            'Hu Yifei',
            'Lu ziqiao'
        ],
        [Symbol.iterator](){
            let index = 0;
            let _this = this;
            return {
                next:function(){
                    if (index < _this.name.length) {
                        const result = { value: _this.name[index], done: false };
                        index++;
                        return result;
                    }else{
                        return {value: undefined, done: true};
                    }
                }
            }
        }
    }
    
    for(let val of AiQing){
        console.log(val);
    }
    
    //------Traversal result-------------
    //Zeng Xiaoxian
    //Hu Yifei
    //Lu ziqiao

To make for of easier to use, many types in ES6 have default iterators. All collection types (that is, arrays, maps, and sets) have iterators.

generator

1. Generator definitions and calls

Generator is actually a special function for asynchronous programming, which can be called in the way of iterator. The definition of the generator can be represented by a * in front of the function name. The result returned by the generator function is the iterator object, and the result of calling the iterator objectnextMethod can be obtainedyieldValue after statement:

function * generate(){
    console.log(111);
    Yield 'disciple Dongsheng Shenzhou Aolai guohuaguo mountain shuilian cave people's surname';
    console.log(222);
    Yield 'OK! OK! OK! From now on, it is called "Monkey King";
    console.log(333);
    Yield 'never dare to mention the word master, just say it's my own meeting';
    console.log(444);
}

//Call step by step using the iterator method
let iterator = generate();
console.log(iterator.next());  
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());

//For... Of... Traversal
 for(let v of generate()){
     console.log(v);
 }

2. Generator function parameters

Note the frontyieldThe execution result of is the input parameter of the following expression.

function * generate(params){
    console.log(params);
    Let one = yield 'first step'// The execution result of the previous yield is the input parameter of the following expression
    console.log(one);
    Let two = yield 'step 2';
    console.log(two);            
}

//The first parameter is passed in parentheses after the calling function name
Let iterator = generate ('wukong Xueyi 111 ');
console.log(iterator.next());
//Other parameters are passed in through the next method
Console.log (iterator. Next ('wukong Xueyi 222 ');
Console.log (iterator. Next ('wukong Xueyi 333 ');        
console.log(iterator.next());

3. Solve the case of asynchronous callback

When developing a project, we often obtain commodity data. We often need to obtain order data and user data first, which have a certain dependency. The implementation scheme of this asynchronous callback is as follows:

//Simulate obtaining user data, order data and commodity data 
function getCustomer(params){
    setTimeout(()=>{
        console.log(params);
        Let data = 'user data';                
        //Call the next method and pass in the data
        iterator.next(data);
    }, 1000);
}

function getOrders(params){
    setTimeout(()=>{
        console.log(params);
        Let data = 'order data';
        iterator.next(data);
    }, 1000)
}

function getGoods(params){
    setTimeout(()=>{
        console.log(params);
        Let data = 'commodity data';
        iterator.next(data);
    }, 1000)
}

function * generate(params){
    let customer = yield getCustomer(params);
    let orders = yield getOrders(customer);
    let goods = yield getGoods(orders);
}

//Call generator function
Let iterator = generate ('customer name ');
iterator.next();

Promise

1. Define promise object

const p = new Promise(function(resolve, reject){
    setTimeout(function(){
        //Resolve ('function called when asynchronous acquisition succeeds');
        Reject ('function called when asynchronous acquisition fails');  
    }, 1000);
});

p.then(function(value){
    console.log(value);
}, function(err){
    console.error(err);
})

2. Read file with promise package

//Introducing FS module
const fs = require('fs');

//Use promise encapsulation
const p = new Promise(function(resolve, reject){
    fs.readFile("./readme.txt", (err, data)=>{
        //Judge if it fails
        if(err) reject(err);
        //If successful
        resolve(data);
    });
});

p.then(function(value){
    console.log(value.toString());
}, function(err){
    Console.log ("read failed!!");
});

3. Encapsulating Ajax with promise

const p = new Promise((resolve, reject) => {
    //1. Create object
    const xhr = new XMLHttpRequest();

    //2. Initialization
    xhr.open("GET", "http://url");

    //3. Send
    xhr.send();

    //4. Bind the event and process the response result
    xhr.onreadystatechange = function () {
        //Judge
        if (xhr.readyState === 4) {
            //Judge响应状态码 200-299
            if (xhr.status >= 200 && xhr.status < 300) {
                //Indicates success
                resolve(xhr.response);
            } else {
                //If it fails
                reject(xhr.status);
            }
        }
    }
})

//Specify callback
p.then(function(value){
    console.log(value);
}, function(reason){
    console.error(reason);
});

4. Promise asynchronous call case

The simulation first obtains the user data, takes the user data to obtain the order data, and finally takes the order data to obtain the commodity data.

const p = new Promise((resolve, reject) => {
    setTimeout(()=>{
        Let data = 'user data';   
        console.log(data);
        resolve(data); 
    }, 1000);
});

p.then(value => {
    return new Promise((resolve, reject) => {
        setTimeout(()=>{
            Let data = 'order data';   
            console.log(data);
            resolve(data); 
        }, 1000);
    });
}).then(value => {
    return new Promise((resolve, reject) => {
        setTimeout(()=>{
            Let data = 'commodity data';   
            console.log(data);
            resolve(data); 
        }, 1000);
    })
}).then(value => {
    Console.log ('final: '+ value);
}).catch(err=>{
    console.error(err);
});

Set set

1. Create a set collection

let s = new Set(); // Null data
Let S2 = new set (['Luffy', 'Solon', 'Nami', 'Yamaji'])// Create with array

2. Set set common operations

Let S2 = new set (['Luffy', 'Solon', 'Nami', 'Yamaji']);        

//Number of elements
console.log(s2.size);
//Add new element
S2. Add ('usop ');
//Delete element
S2. Delete ('solon ');
//Check whether it contains any elements
Console.log (S2. Has ('solon ');
//Empty
s2.clear();

//Loop through the set set
for(let v of s2){
    console.log(v);
}

3. Set set practice case

//Array de duplication, using the extension operator and the feature that the set set does not store the same elements
let arr = [1,2,3,4,5,2,3,3,1];
let arr2 = [...new Set(arr)];
console.log(arr2);    

//The union of two arrays,
let arr = [1,2,3,4,5,2,3,3,1];
let arr2 = [3,4,5,6,7];
let res = [...new Set([...arr, ...arr2])]
console.log(res);

//Find intersection
let arr = [1,2,3,4,5,2,3,3,1];
let arr2 = [3,4,5,6,7];
let s2 = new Set(arr2);
let res = [...new Set(arr)].filter(data => {
    if(s2.has(data)){
        return true;
    }else{
        return false;
    }
});
console.log(res);    

//Difference set
let arr = [1,2,3,4,5,2,3,3,1];
let arr2 = [3,4,5,6,7];
let s2 = new Set(arr2);
let res = [...new Set(arr)].filter(data => {
    if(s2.has(data)){
        return false;
    }else{
        return true;
    }
});
console.log(res);

Map set

1. Map creation

let m = new Map();

2. Map operation

//Add data to map
m.set('key','value');
m.set('arr',[1,2,3]);
m.set('function',function(){
    Console.log ('store function in map ')
});
m. Set ('object ', {obj': 'object'} stored in map);

console.log(m.size);

//Delete
m.delete('key');
console.log(m);

//Get map data
console.log(m.get('arr'));
m.get('function')();
console.log(m.get('object')['obj']);

//Empty map
 m.clear();

//Traversal
for(let v of m){
    console.log(v);
}

Class declaration

1. Class creation

classDeclare classes,constructorDefine constructors,newCalled when creating object initialization

class Cat{
    //Pass in object properties through constructor
    constructor(name,age){
        Console.log ("I will be called during new");
        this.name = name;
        this.age = age;
    }

    introduce(){
        Console.log ("my name is:" + this. Name + "and my age is:" + this. Age ");
    }

}    

let cat1= new Cat('ketty',2);
cat1.introduce();

2. Inherit parent class

useextendsInherit parent class, usingsuperThe parent constructor method is called, and the method of the parent class can be overridden.

//Parent class
class Animal{
    constructor(name,age){
        Console.log ("the parent constructor is called");
        this.name = name;
        this.age = age;
    }

    eat(){
        Console.log (this. Name + "like to eat");
    }
}

//Subclass
class Cat extends Animal{
    //The object attribute is passed in through the constructor, and through super (name, age); Pass parameters to parent class
    constructor(name,age,height){
        super(name,age); 
        Console.log ("subclass constructor called");            
        this.height = height;
    }

    //eat(){
    //Console.log ("subclass" + this. Name + "like to eat");
    //}
        
    introduce(){
        Console.log ("my name is:" + this. Name + ", age is:" + this. Age + ", height is:" + this. Height ");
    }
}    

//Create subclasses and call parent and subclass methods
let cat1= new Cat('ketty',2 , 188);
console.log(cat1);
cat1.introduce();
cat1.eat();

3. Static member of class

Static members of a class can only be accessed through the class name, not through the instance object of the class

class Animal{        
    static name = 'dog';
    static eat(){
        Console.log ('Want to eat ham sausage ');
    }
}

console.log(Animal.name);
Animal.eat();

ES6 modularization

1. Ways to expose data

//Separate exposure
Export let name = 'journey to the West';
export function action() {
    Console.log ("learning lessons");
}

//Unified exposure
Let name = 'journey to the West';
function action() {
    Console.log ("learning lessons");
}
export {name, action};

//Default exposure
export default {
    Name: 'journey to the West',
    action: function(){
        Console.log ("learning lessons");
    }
}

2. Import data

//1. General import method
import * as m1 from "./m1.js";

//2. Deconstruction of assignment form
import {school, teach} from "./m2.js";

//3. Default exposure introduction method
import m3 from "./m3.js";

What’s new in ES7

1、Array.prototype.includes
IncludesMethod is used to detect whether an element is contained in the array (there is no sense ratio)indexof(easy to use)

Const arr = ['Wukong', 'Bajie']
Console.log (arr.includes ('wukong ')// true

2. Exponential operator**
Introducing exponential operator**Used to realize power operation, function andMath.pow()identical

console.log(2 ** 10); // The result is 1024

Async and await

asyncandawaitClassic application scenarios, sendingAJAXRequest.

//Send an Ajax request, and the result returned is the promise object
function ajaxUtil(url) {
    return new Promise((resolve, reject) => {
        //1. Create object
        const x = new XMLHttpRequest();
        //2. Initialization
        x.open('GET', url);
        //3. Send
        x.send();
        //4. Event binding
        x.onreadystatechange = function () {
            if (x.readyState === 4) {
                if (x.status >= 200 && x.status < 300) {
                    //Success
                    resolve(x.response);
                }else{
                    //If it fails
                    reject(x.status);
                }
            }
        }
    })
}    

//Async and await test Axios
async function test(){
    //Send Ajax request
    let result1 = await ajaxUtil("https://api.apiopen.top/getJoke");
    console.log(result1);
    let result2 = await ajaxUtil("https://api.apiopen.top/getJoke");
    console.log(result2);
}
test();