ES6 Usage Summary

Time:2021-7-28

Destructuring assignment

  • Realize variable exchange
let a =1;

let b=2

[a,b]=[b,a]

console.log(a,b)//2,1
  • Default value assignment
[a,b,c=3]=[1,2]
console.log(a,b,c)//1,2,3
function fc(){
  return [1,2]
}
let a,b;
[a,b]=fc()
console.log(a,b)//1,2
  • Nested deconstruction assignment of objects
let metadata={
title:'currentTitle',
test:[{
title:"deepTitle",
desc:'description'
}]
}
let {title:titleone,test:[{title:titlescond}]}=metadata;
console.log(titleone,titlescond)//currentTitle,deepTitle

String extension

If the Unicode code is greater than 0xfff, the codepoint matching method needs to be used for operation
String.includes
String.startsWith
String.endsWith
Template string:

let name="list"
let info="hello world"
let m=`i am ${name}',${info}`
console.log(m)// i am list,hello world

Padstart: fill in 1. String. Padstart (length, ‘char’) / / pass a supplementary char based on the current character, and the returned length is length
Padend: fill in blank after / / pass a supplementary char based on the current character, and the returned length is length
Label template:
let user={
name:”list”,
info:”hello world”
};
console.log(abci am ${user.name},$(user.info))
function abc(s,v1,v2){
return s+v1+v2
}

Array extension

let arr =Array.of(3,4,7,9,11)
console.log('arr=',arr)
}//Array generation
{
  Array. From // convert pseudo array into array
let p=document.querySelectorAll("p")
let pArr=Array.from(p)
pArr.forEach{
function(item){
console.log(item.textContent)}}
}
Array from can also implement functions similar to map
console.log(Array.from([1,3,5],function(item){return item*2}))

Array. Keys() traverses Subscripts
Array. Values() traverses the values
Array. Entries()

{
console.log([1,2,3,4,5].copyWithin(0,3,4))//[4,2,3,4,5]
/*
Param1: replaced subscript
Param2: the starting subscript of the replacement,
Param3: end subscript of replacement (left closed right open)
When the length of the replacement plus the starting point subscript + 1 is greater than the length of the array, the excess will not be replaced circularly
console.log([1,2,3,4,5].copyWithin(3,1,4))//[1,2,3,2,3]
*/
}

[1,2,3,4,5,6]. Find (function (item) {return item > 3}) // 4, only the first matching value will be returned
[1,2,3,4,5,6]. FindIndex (function (item) {return item > 3}) // 3, only one matching subscript will be returned
[1,2,NaN].includes(1)//true
[1,2,NaN].includes(NaN)//true

Extension function

  • Function defaults
function test(x,y=10){
Console.log ('default ', x, y)
}
test("hello")//hello 10

*The default value cannot be followed by a variable without a default value

Function test3 (x, y = 10, z) // wrong
  • Res parameter
function test3(...args){
for(let v of args){
console.log("rest",v)
}}
test3(1,2,3,4,'a')
  • Extension operator
{
console.log(...[1,2,4])//1 2 4
}
  • Arrow function

Complete arrow function

()=>{
return XXXX
}

Only return can be omitted

let arrow =v=>v*2
console.log('arrow',arrow(3))//6

This binding problem(unknown JS reading notes)

  • Tail call
{
function tail(x){
  console.log('tail',x)
}
function fx(x){
  return tail(x)
}
}
fx(123)//123

Object extension

  • Concise representation
{
let o=1;
let k=2;
let es5={
    o:o,
    k:k
}
}Equivalent to
let es6={
    o,k
}
let es5_function={
  hello:function(){
  console.log('hello')
}
let es6_function={
  hello(){
  console.log('hello')
}}}
  • Attribute expression
let a ='b'
let es6_obj={
  a:'c'
};
let es6_obj={
  [a]:'c'
}
console.log(es6_obj)//{b:'c'}
  • New API
Object. Is ('array '), object. Is ([], [], [] = []) // true is method (equivalent to = = =)

Object.assign({a:a},{b:'b'})//{a:'a',b:'b'};// Shallow copy


let test ={k:123,o:456};
for(let [key,value] of Object.entries(test)){
  console.log([key,value])
}//The traversal of ["K", 123] ["O", 123] objects is similar to that of arrays
*Object. Values is similar to arrays, and Babel support is not friendly*

//The extension operator * Babel support is also unfriendly*
let {a,b,...c}={a:'test',b:'kill',c:'ddd',d:'ccc'}
c={
c:'ddd',
d:'ccc'
}

Symbol data type

  • Provide a unique value
let a1=Symbol();
let a2=Symbol();
Console.log (A1 = = A2) false // can never be equal
let a3=Symbol.for('a3')
Let A4 = symbol. For ('a3 ') // method of obtaining symbol
console.log(a3===a4)true
Actual use
let a1=Symbol.for('abc')
let obj={
[a1]:'123',
'abc':345,
'c':456
}
for (let [key,value] of Object.entries(obj)){
  console.log('let of ',key value)
}//ABC 345 C 456 cannot get the element with symbol as the key value
Object.getOwnPropertySymbols(obj).forEach(function(item){
  Console.log (obj [item]) // 123 get the symbol key
})
Reflect.ownkeys(obj).forEach(function(item){
  Console.log (ownkeys, obj [item]) // this method can get all the values
})

data structure

  • Set

Elements in the set collection cannot be duplicated

The length in the set is expressed in size
let list = new Set()
list.add(5)
list.add(7)
console.log("size",list.size)//2 

You can use set to remove the duplicate
let list = new Set()
list.add(1)
list.add(2)
list.add(1)
console.log("list ",list )//1,2
  • weakSet

Weakset: only objects can be placed, weak references cannot be traversed, no size attribute, no clear attribute

  • Map

Key can be any type
let map =new Map()
let arr=[‘123’]
map.set(arr,456)
console.log(‘map’,map,map.get(arr))// {[“1230″=>456]} 456

{
let map= new Map([‘a’,123],[‘b’,456]);
console.log(‘map arg’)//{‘a’=>123,’b’=>456}
//Get length size
//Get value get
//Delete delete
//Clear
}

  • weakMap

The relationship is consistent with the relationship between set and weakset

Addition, deletion, modification and query of set map array
  • increase
map.set("t",1)
set.add({"t":1})
array.push({t:1})
  • Delete
map.delete('t')
set.forEach(item=>item.t?set.delete(item):' ')
let index=array.findIndex(item=>{item.t})
array.splice(index,1)
  • change
map.set('t',2)
set.forEach(item=>item.t?item.t=2:'')
array.forEach(item=>item.t?item.t=2:' ')
  • check
let map_exist=map.has('t')
let set_exist=set.has({t:1})
let array_exist=array.find(item=>item.t)

Proxy and reflect

Proxy wrapper object

{
let obj ={
time:'2017-03-11',
name:'net',
_r:123
}
let monitor =new Proxy(obj,{
//Read
  get(tartget,key){
  return target[key].replace('2017',2018)
}
//Set
  set(target,key,value){
  if(key==='name'){
    return target[key]=value
}else{
    return tartget[key]
}
}
//Intercepting key in obj
  has(target,key){
  if(key==='name'){
  return target[key]
}else{
  return false;
}
  }
//Intercept delete
deleteProperty(target,key){
  if(key.indexof('_')>-1){
  delete target[key];
  return true
}
else{
  return target[key]  
}
}
//Intercept object.keys, object.getownpropertysymbols, object.getownpropertynames
ownKeys(target){
  return Object.keys(target).filter(item=>item!='time')  
}
      })
Console.log ('Get ', monitor. Time) // get properties in proxy on March 11, 2018
Monitor. Time = 2018 // will not take effect
Monitor. Name ='xi '// effective
console.log('has','name' in monitor,'time' in monitor )//true false
delete monitor.time
Console.log ('delete ', monitor) // deletion failed
delete monitor._r
Console.log ('delete ', monitor) deleted successfully
console.log('ownKeys',Object.keys(monitor));// There will be no time in convenience
}
Proxy is equivalent to an interceptor, which modifies the operation before the user actually operates on an object

Reflect wrapper object

{
let obj={
  time:'2017-03-11',
  name:'net',
  _r:123
}
 console.log('Reflect get',Reflect.get(obj,'time'));// Similar to all proxy methods
}

Use proxy and reflec as a verifier

function validator(target, validator) {
    return new Proxy(target, {
        _validator: validator,
        set(target, key, value, proxy) {
            if (taget.hasOwnProperty(key)) {
                let va = this._validator[key];
                if (!!va(value)) {
                    return Reflect.set(target, key, value, proxy)
                }
                else {
                    Throw error ('cannot set ${key} to ${value} ')
                }
            } else {
                Throw error (` ${key} does not exist `)
            }
        }
    })
}
const personvalidators = {
    name(val) {
        return typeof val === 'string'
    },
    age(val) {
        return typeof val === 'number' && val > 18
    }
}
class Person {
    constructor(name, age) {
        this.name = name
        this.age = age
        return validator(this, personvalidators)
    }
}
const person = new Person('lilei', 30)
console.log(person)//Proxy{name:"lilei",age:"30"}
person.name=48;// Cannot set name to 48

Classes and objects in ES6

{
    class Parent {
        constructor(name = "heiheihie") {
            this.name = name
        }
    }
    class child extends Parent {
        constructor(name = 'child') {
            super(name)
        }
    }
}

Promise

  • Traditional callback
//Disadvantages of asynchronous operation: the multi-level callback code structure will be particularly obscure
{
    //Basic definition
    let ajax = function (callback) {
        Console.log ("execute")
        setTimeout(() => {
            callback && callback()
        }, 1000);
    }
    ajax(function () {
        console.log("timeout1")
    })
    //Execute timeout1

}
  • Promises basic usage
{
    let ajax = function () {
        Console.log ("execute 2")
        return new Promise(function (resolve, reject) {
            if (true) {
                setTimeout(() => {
                    resolve()
                }, 1000)
            }
            else {
                reject()
            }
        })
    }
    ajax().then(function () {
        console.log('promise', 'resolve')
    }, function () {
        console.log("promise", "reject")
    })
}
  • Promise based multiple callback calls
{
    let ajax = function () {
        Console.log ("execute 3")
        return new Promise(function (resolve, reject) {
            setTimeout(() => {
                Console.log ("first resolve")
                resolve()
            }, 1000)
        })
    }

    ajax()
        .then(
            function () {
                return new Promise(function (resolve, reject) {
                    setTimeout(() => {
                        Console.log ("second resolve")
                        resolve()
                    }, 2000)
                })
            })
        .then(function () {
            console.log('timeout3')
        })
}

ES6 Usage Summary

  • Exception capture
{
    let ajax = function (num) {
        Console.log ("execute 4")
        return new Promise(function (resolve, reject) {
            if (num > 5) {
                resolve()
            }
            else {
                Throw new error
            }
        })
    }
    ajax(10).then(function () {
        console.log("log", 10)
    }).catch(function (err) {
        console.log('catch', err)
    })

    ajax(3).then(function () {
        console.log("log", 3)
    }).catch(function (err) {
        console.log('catch', err)
    })

}

All and race methods in promise
**The then method is executed only when all instances in the all method return resolve
Take the following code as an example. The DOM operation will not be performed until all images are loaded**

{
    function loadImg(src) {
        return new Promise((resolve, reject) => {
            let img = document.createElement('img')
            img.src = src
            img.onload = function () {
                resolve()
            }
            img.onerror = function (err) {
                reject(err)
            }
        })
    }
    function showImgs() {
        imgs.forEach(function (img) {
            document.body.appendChild(img)
        })
    }
    Promise.all([
        loadImg('xxxxxxxxxxxxxxxxxxxxxxxxxxx'),
        loadImg('xxxxxxxxxxxxxxxxxxxxxxxxxxx'),
        loadImg('xxxxxxxxxxxxxxxxxxxxxxxxxxx')
    ]).then(showImgs)

}

When an instance of the race method returns resolve, the then method is executed

Iterator and loop

When a for… Of loop is used to traverse a data structure, the loop will automatically look for the iterator interface.
ES6 stipulates that the default iterator interface is deployed in the symbol.iterator attribute of the data structure, or a data structure can be considered “iteratable” as long as it has the symbol.iterator attribute.
Some data structures in ES6 have a native iterator interface (such as an array), that is, they can be traversed by a for… Of loop without any processing. The reason is that these data structures natively deploy the symbol.iterator attribute (see below), while some other data structures do not (such as objects). All data structures that deploy the symbol. Iterator attribute are called deployed ergodic interfaces. Calling this interface will return an iterator object( The whole paragraph is taken from the introduction to ES6)
The data structures born with the iterator interface are:
Array
Map
Set
String
TypedArray
Arguments object for function
NodeList object

let arr = ['a', 'b', 'c'];
let iter = arr[Symbol.iterator]();

iter.next() // { value: 'a', done: false }
iter.next() // { value: 'b', done: false }
iter.next() // { value: 'c', done: false }
iter.next() // { value: undefined, done: true }

Add an ergodic interface to the object

let obj = {
  data: [ 'hello', 'world' ],
  [Symbol.iterator]() {
    const self = this;
    let index = 0;
    return {
      next() {
        if (index < self.data.length) {
          return {
            value: self.data[index++],
            done: false
          };
        } else {
          return { value: undefined, done: true };
        }
      }
    };
  }
};

Generator

//Role of generator

{
    let tell = function* () {
        yield 'a';
        yield 'b';
        return 'c'
    }
 /*
//Async and await are equivalent * and yield are their syntax sugar
let tell =async function() {
        await 'a';
        await 'b';
        await 'c'
    }
*/
    let k = tell();
    console.log(k.next())
}
//It can be understood that the generator can disassemble a function and execute it asynchronously

Create the traversal interface iterator of the object by creating the generator function

{
   let obj = {}
   obj[Symbol.iterator] = function* () {
       yield 1;
       yield 2;
       yield 3;
       for (let value of obj) {
           console.log('value', value)
       }
   }
}

//Use generator to realize lottery logic and reduce unsafe global variables

<!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>Document</title>
</head>

<body>
    <script>
        let draw = function (count) {
            Console.log (` current remaining ${count} times')
        }
        let residue = function* (count) {
            while (count > 0) {
                count--;
                yield draw(count)
            }
        }
        let start = residue(5)
        let btn = document.createElement('button')
        btn.id = 'start'
        Btn.textcontent = "lucky draw"
        document.body.appendChild(btn)
        document.getElementById('start').addEventListener('click', function () { start.next() }, false)
    </script>
</body>
</html>

Implement polling using generator

     let ajax = function* () {
            yield new Promise(function (resolve, reject) {
                setTimeout(() => {
                    resolve({ code: 1 })
                }, 200);
            })
        }
        let pull = function () {
            let generator = ajax();
            let step = generator.next()
            step.value.then(function (d) {
                if (d.code != 0) {
                    setTimeout(() => {
                        console.log('wait')
                        pull()
                    }, 1000)
                }
                else {
                    console.log(d)
                }
            })
        }
        pull()

Decorator

Definition: a function used to modify the behavior of a class
//Basic usage

{
    let readonly=function(target,name,descriptor){
      descriptor.writable=false
      return descriptor  
    };
    class Test{
        @readonly
        time(){
            return '2019-03-18'
        }
    }
    let test=new Test();
    console.log(test.time())// "2019-03-18"
    test.time=function(){
        console.log('reset time')
    }
    console.log(test.time())//cannot assign to read only property 'time' of object '#Test'
}
{
    let typename=function(target,name,descriptor){
        target.myname='hello'
      };
      @typename
      class Test{

      }
      Console.log ('class modifier ', test. Myname) // class modifier hello
}

Third party decorator library core decorators
https://www.npmjs.com/package…

modularization

//Already familiar

This article is based on the example of ES6 zero basic teaching on muke.com (the iterator part is taken from the introduction to ES6)
https://coding.imooc.com/clas…
Manually tap the code to enhance your memory
The video gives a simple introduction and practical examples of ES6 syntax with a separate example
For promise, decorator, generator and other parts, separate reinforcement learning is also required.
It’s like going into the sea!

Recommended Today

Implementation example of go operation etcd

etcdIt is an open-source, distributed key value pair data storage system, which provides shared configuration, service registration and discovery. This paper mainly introduces the installation and use of etcd. Etcdetcd introduction etcdIt is an open source and highly available distributed key value storage system developed with go language, which can be used to configure sharing […]