A summary of the new features of es6

1.let & const

  1. let, similar to var, is used to declare variables

characteristic:

  1. let cannot declare variables repeatedly, var can declare variables repeatedly;
  2. Block level scope: there are global scope, function scope and eval scope in es5; Block level scope is introduced in es6, and the variables declared by let are valid in the block level scope {}
  3. The variable declared by let does not have the variable promotion problem of var

for instance:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div class="container">
        <h2 class="page-header">Click to switch colors</h2>
        <div class="item">1</div>
        <hr>
        <div class="item">2</div>
        <hr>
        <div class="item">3</div>
    </div>

    <script>
        // Get div object
        let items = document.getElementsByClassName('item')

        // When traversing and binding events, let i
        for(let i = 0; i < items.length; i++){
            items[i].onclick = function(){
                items[i].style.background = 'pink'
            }
        }
        /*
        It is equivalent to declaring i in three block level scopes respectively
        {
            let i = 0
            items[i].onclick = function(){
                items[i].style.background = 'pink'
            }
        }
        {
            let i = 1
            items[i].onclick = function(){
                items[i].style.background = 'pink'
            }
        }
        {
            let i = 2
            items[i].onclick = function(){
                items[i].style.background = 'pink'
            }
        }
        */

        /*
        // var i when traversing and binding events
        for(var i = 0; i < items.length; i++){
            items[i].onclick = function(){
                // Modify the background color of the current element
                this.style.background = 'pink' // Here this points to the 'bound element object', that is, the object calling the function
                // Items [i] cannot be used here as above style. background = 'pink',
                // Because the i of var does not consider the block level scope, it is equivalent to declaring a variable globally. After the loop ends, i=3,
                // When the function is executed, look for the upper layer, and finally get the global variable i=3, and the items[3] is undefined
            }
        }
        amount to
        {
            var i = 0
            // ...

        }
        {
            var i = 1
            // ...
        }
        {
            var i = 2
            // ...
        }
        {
            var i = 3
        }

        */
    </script>
</body>

<style>
    .item{
        width: 200px;
        height: 50px;
        border-radius: 2%;
        background-color: brown;
    }
</style>

</html>
  1. const is used to declare constants

matters needing attention:

  1. The initial value must be assigned
  2. General constants are capitalized (belonging to the programming specification)
  3. Constant value cannot be modified
  4. Block level scope exists
  5. For the element modification of arrays and objects, it does not count as the modification of constants and no error will be reported (because the reference data type saves the memory address, const declaration can be used when declaring arrays and objects to ensure that the saved memory address remains unchanged)

2. Deconstruction assignment

ES6 allows you to extract values from arrays and objects according to a certain pattern and assign values to variables

  1. Deconstruction of array
        const Web = ['html', 'css', 'javascript']
        let [tool1, tool2, tool3] = Web

        console.log('tool1-----', tool1) // html
        console.log('tool2-----', tool2) // css
        console.log('tool3-----', tool3) // javascript
  1. Deconstruction of objects
        const liMing = {
            name: 'liMing',
            age: '22',
            tell: function(){
                console.log(`I am liMing`)
            }
        }

        let {name, age, tell} = liMing

        console.log(name) // 'liMing'
        console.log(age) // '22'
        console.log(tell) // f(){...}
        tell() // I am liMing

3. Template string

characteristic:

  1. `A newline character can appear directly in the ` (backquote) content, but not in the '' and '', which will report an error
  2. Variable splicing can be carried out directly

4. Simplify object writing

ES6 allows variables and functions to be written directly in curly braces as attributes and methods of objects (when the attribute name and variable name are the same), which is more concise

        let name = 'LiMing'
        let tell = function(){
            console.log('I am LiMing')
        }

        const liMing = {
            name,
            tell,
            sayHi(){
                console.log('hello')
            }
        }

        // Equivalent to
        // const liMing = {
        //     name: name,
        //     tell: tell,
        //     sayHi: function(){
        //         console.log('hello')
        //     }
        // }

        console.log(liMing)
        liMing.tell()
        liMing.sayHi()

5. Arrow function

Difference from function declaration:

  1. The arrow function this is static.

    • This in the arrow function points to the upper object; Always point to the value of this under the scope where the function is declared. It cannot be changed by call

    • this in a normal function points to the object whose function is called

      function getName(){
          console.log(this.name)
      }
      
      let getName2 = ()=>{
          console.log(this.name)
      }
      
      // Set the name attribute of the window object
      window.student = 'LiMing'
      const student = {
          name: 'HanMei'
      }
      
      // Direct call
      getName() // LiMing
      getName2() // LiMing
      
      // Call method call
      getName.call(student) // HanMei
      getName2.call(student) // LiMing
      
  2. An arrow function cannot instantiate an object as a constructor

        let Person = (name, age)=>{
            this.name = name
            this.age = age
        }
        let me = new Person('LiMing', 20) // Error: Uncaught TypeError: Person is not a constructor
    
  3. The arrow function cannot use the arguments variable, but you can use rest

        let fn = ()=>{
            console.log(arguments)
        }
    
        fn(1, 2, 3) // Error: Uncaught ReferenceError: arguments is not defined
        
    
        let fn2 = (...rest)=>{
            console.log(...rest)
        }
    
        fn2('a','b','c') // a b c
    
  4. Abbreviation for arrow function
    ① When there is only one formal parameter, it can be omitted ()
    ② When there is only one statement in the contemporary code body, {} can be omitted. At this time, return must be omitted, and the execution result of the statement is the return value of the function

        // When there is only one formal parameter, you can omit ` ()`
        let add = n => {
            return n + n
        }
    
        console.log(add(9))
    
        // When there is only one statement in the contemporary code body, you can omit '{}'. At this time, 'return' must be omitted, and the execution result of the statement is the return value of the function
        let pow = n => n*n
    
        console.log(pow(9))
    

5. Example of arrow function
The arrow function is suitable for callbacks unrelated to this, such as timer setTimeout (() = > {...}, 2000). Array method callback arr.filter ((item) = > {...});
It is not suitable for callbacks related to this, such as the event callback ad.addEventListener('click', function() {...} Method definition in object {name: 'LiMing', getName: function(){this.name}}
Example 1:

        // Demand - 1 click div 2s and the color turns red
        
        // Get element
        let ad = document.getElementById('ad')
        // Binding event
        ad.addEventListener('click', function(){
            setTimeout(function(){
                console.log(this) // this in the timer points to window
                this.style.background = 'brown' // report errors
            }, 2000)
        })

        //Solution 1
        // ad.addEventListener('click', function(){
        //     //Save the value of this
        //     let _this = this // _this points to ad
        //     setTimeout(function(){
        //         console.log(_this) 
        //         _this.style.background = 'brown'
        //     }, 2000)
        // })

        // Solution 2
        // ad.addEventListener('click', function(){
        //     setTimeout(()=>{
        //         console.log(this) 
        //         this.style.background = 'brown' // this refers to the value of this under the scope where the function is declared, i.e. ad
        //     }, 2000)
        // })

Example 2:

        // Requirement - 2 returns an even number of elements from the array
        const arr = [1, 6, 9, 10, 100, 25]
        const result = arr.filter(function(item){
            if(item %2 === 0){
                return true
            }else{
                return false
            }
        })

        // You can use the arrow function
        // const result = arr.filter(item => {
        //     if(item % 2 === 0){
        //         return true
        //     }else{
        //         return false
        //     }
        // })
        // It can also be abbreviated as
        // const result = arr.filter(item => item % 2 === 0)

        console.log(result)

6. Default value setting of function parameters

ES6 allows you to assign initial values to function parameters

        function add(a, b, c=10){ // Parameters with default values are generally placed at the back
            return a + b + c
        }
        console.log(add(1,2,))

Can be used with deconstruction assignment

        function connect({host='127.0.0.1', port, username, password}){
            console.log(host, port)
            console.log(username, password)
        }
        
        connect({
            port: 3306,
            username: 'root',
            password: 'root',
        })

7.rest parameters

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

        // ES5 how to get arguments
        function printStudent(){
            console.log(arguments) // arguments is an object
        }
        printStudent('LiMing','HanMeimei')

        // ES6 how to get arguments
        function printFriend(friend1, friend2, ...rest){ // The rest parameter must be placed at the end of the formal parameter list, otherwise an error will be reported
            console.log(friend1) 
            console.log(friend2) 
            console.log(rest) // Get an array, you can use the array api
        }
        printFriend('kitten','puppy','rabbit','duck')
        // kitten
        // puppy
        // ['rabbit', 'duck']

8. Extension operator

... Can convert "array" into comma separated "parameter sequence"
Note: Although the form is similar to the rest parameter, the rest parameter is used for the position of the formal parameter when the function is defined, and the extension operator is used for the position of the actual parameter when the function is actually called

        const STUDENTS = ['Xiao Ming','Xiao Fang','Xiao Hong']
        function printStudent(){
            console.log(arguments)
        }

        printStudent(STUDENTS) // The parameter is an array, which contains three elements
        printStudent(...STUDENTS) // The parameter is 3 elements

Application scenario:

  1. Merging of arrays

        const STUDENTS1 = ['Xiao Ming','Xiao Fang','Xiao Hong']
        const STUDENTS2 = ['Xiao Wu', 'Xiao Wang']
    
        // es5 writing method
        const STUDENTS_ES5 = STUDENTS1.concat(STUDENTS2)
        // es6 writing method
        const STUDENTS_ES6 = [...STUDENTS1, ...STUDENTS2]
    
        console.log('es5------',STUDENTS_ES5)
        console.log('es6------',STUDENTS_ES6)
    
  2. Cloning of arrays

        const STUDENTS1 = ['Xiao Ming','Xiao Fang','Xiao Hong']
    
        const PUPIL = [...STUDENTS1] // Note: if the elements in the array are of reference type, the memory address is copied, which is a shallow copy
        console.log('PUPIL----',PUPIL)
    
  3. Convert a pseudo array to a real array

        const divs = document.querySelectorAll('div')
        console.log(divs) // The divs obtained here is actually an object
    
        const divsArr = [...divs] // Turn it into a real array, so that you can use the api of the array, such as filter and map
        console.log(divsArr)
    

9.Symbol

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

Symbol features:

  1. The value of Symbol is unique, which is used to solve the problem of naming conflict
  2. Symbol value cannot be calculated with other data or with itself, such as +, -, *, /, and comparison
  3. The object properties defined by Symbol cannot be traversed by using for... in, but you can use reflect Ownkeys to get all the key names of the object

Create Symbol:

  1. let s2 = Symbol('zhang San ') is used to create a Symbol, and' Zhang San 'is used as a Symbol description, which is equivalent to annotation. Even if the incoming description is consistent, the actual returned value of the Symbol created in this way is different

        // Create Symbol
        let s = Symbol()
        console.log(s,typeof s) // Symbol() "symbol"
    
        let s2 = Symbol('Zhang San') // 'Zhang San' as a Symbol description is equivalent to annotation
        let s3 = Symbol('Zhang San') // Even if the incoming descriptions are consistent, the actual returned values are different
        console.log(s2 === s3) // false
    
  2. Through Symbol For() creates a Symbol. This method creates a Symbol. The incoming description is consistent and the actual returned value is consistent. You can get a unique Symbol value

        // Symbol.for create symbol
        let s4 = Symbol.for('Zhang San')
        let s5 = Symbol.for('Zhang San')
        console.log(s4 === s5) // true
    

Symbol usage scenario

  1. Add properties and methods to the object. Because the Symbol value is unique, you can safely add properties and methods to the object, as shown below

        let game = {
            up: 'upp',
            down: 'doown'
        }
    
        let methods = {
            up: Symbol(),
            down: Symbol(),
        }
    
        // Add method
        game[methods.up] = function(){
            console.log('up up up')
        }
        game[methods.down] = function(){
            console.log('down down down')
        }
    
        console.log('game----', game)
        // call
        game[methods.up]()
    
    
        let youxi = {
            name: 'Werewolf kill',
            [Symbol('say')]: function(){ // Symbol('say ') cannot be written directly here: function() {...}, Because Symbol('say ') is dynamic, it is different from the fixed' name 'above
                console.log('speak')
            }
        }
    

Symbol built-in value

In addition to defining their own Symbol values, ES6 also provides 11 built-in Symbol values that point to methods used internally in the language, such as

  1. Symbol.hasInstance
    This method is called when other objects use the instanceof operator to determine whether it is an instance of the object

        class Person{
            static [Symbol.hasInstance](param){
                console.log('param----', param)
                console.log('Detection type')
            }
        }
    
        let o = {}
    
        console.log(o instanceof Person)
        // param---- {}
        // Detection type
        // false
    
  2. Symbol.isConcatSpreadable
    Symbol of the object The isconcatspreadable property is equal to a bool value, indicating that the object is used for array Is it possible to expand when prototype()

        const arr1 = [1,2,3]
        const arr2 = [4,5,6]
        arr2[Symbol.isConcatSpreadable] = false // arr2 is not expandable
        const arr = arr1.concat(arr2)
        console.log(arr) // [1,2,3,[4,5,6]]
    
  3. Symbol.unscopables
    This object specifies which attributes will be excluded by the with environment when using the with keyword

  4. Symbol.match
    When str.match(myObject) is executed, if the property exists, it will be called to return the return value of the method

  5. Symbol.replace
    When the object is called by str.replace(myObject) method, the return value of the method will be returned

  6. Symbol.search
    When this object is called by str.search(myObject) method, the return value of this method will be returned

  7. Symbol.split
    When the object is called by str.split(myObject) method, the return value of the method will be returned

  8. Symbol.iterator
    Object for Symbol. Is called when the of loop Iterator method, which returns the default iterator of the object

  9. Symbol.toPrimitive
    When the object is converted to the value of the original type, this method will be called to return the original type value corresponding to the object

  10. Symbol.toStringTag
    When the toString method is called on the object, the return value of the method is returned

  11. Symbol.species
    This property is used when you create a derived object

10. Iterator

Iterator is an interface that provides a unified access mechanism for various data structures. Any data structure can complete the traversal operation as long as the iterator interface is deployed

Traversing ES6 creates a new command The of loop and iterator interface are mainly used for Of consumption
Note: for Of traverses the key value, for In traverses the key name
for...of cannot modify the attribute value. forEach() can

Data with native iterator interface (can be traversed by for...of)

  • Array
  • Arguments
  • Set
  • Map
  • String
  • TypedArray
  • NodeList

working principle:

  1. Create a pointer object to the starting position of the current data structure

  2. When the next method of the object is called for the first time, the pointer automatically points to the first member of the data structure

  3. Next, the next method is called continuously, and the pointer moves back until it points to the last member

  4. Each time the next method is called, an object containing the value and done attributes is returned. The done attribute indicates whether the traversal is over

        const food = ['Yu-Shiang Shredded Pork','sweet and sour fillet of pork','Boiled Fish with Pickled Cabbage and Chili']
        for(let item of food){
            console.log(item)
        }
    
        let iterator = food[Symbol.iterator]()
    
        console.log(iterator.next()) // {value: "shredded pork with fish flavor", done: false}
        console.log(iterator.next()) // {value: "sweet and sour tenderloin", done: false}
        console.log(iterator.next()) // {value: "sauerkraut fish", done: false}
        console.log(iterator.next()) // {value: undefined, done: true} true indicates that the traversal has ended
    

Note: when you need to customize the traversal data, you should think of iterators

Iterator application - Custom traversal data (i.e. manually implementing an iterator)

        // Declare an object
        const school = {
            name: 'Third middle school',
            students: [
                'LiMing',
                'HanMeimei',
                'WangFang',
            ],
            [Symbol.iterator](){
                // Declare an index variable
                let index = 0
                return {
                    next: ()=>{
                        if(index < this.students.length){
                        // if(index < 3){
                            const result = {value: this.students[index], done: false}
                            // Subscript self increment
                            index++
                            // Return results
                            return result
                        }else{
                            return {value: undefined, done: true}
                        }
                    }
                }
            }
        }

        // Traverse this object
        for(let item of school){
            console.log(item)
        }

11. Generator

The generator itself is a special function. The generator function is an asynchronous programming solution provided by ES6, and its syntax behavior is different from that of traditional functions

  • Execute the generator function and return an iterator object through iterator The next() call executes the statement inside the function

        function * gen(){
            console.log('hello generator')
        }
        let iterator = gen() // An iterator object is returned
        // console.log(iterator)
        // Pass The next() call executes the statement inside the function
        iterator.next() // hello generator
    
  • yield is the separator of the function code, which is combined with calling iterator The next () method realizes the segmented execution of the statement of function gen1

        function * gen1(){
            console.log('--- 1 ---')
            yield 'Ears' // Separator for function code
            console.log('--- 2 ---')
            yield 'tail'
            console.log('--- 3 ---')
        }
    
        let iterator1 = gen1()
        iterator1.next() // --- 1 ---
        iterator1.next() // --- 2 ---
        iterator1.next() // --- 3 ---
        // By calling The next() method realizes the segmented execution of the statement of function gen1
    
  • Use for The iterator object returned after the execution of the of traversal function. The item traversed each time is the expression after yield or the value of the argument

        function * gen1(){
            yield 'Ears' // Separator for function code
            yield 'tail'
        }
    
        // Traversal. The item traversed each time is the expression after yield or the value of the argument
        for(let item of gen1()){
            console.log(item)
        }
        // Execution result:
        // Ears
        // tail
    
        // Note: next call and for Of calls exist at the same time, and only the first one will be supported
    
  • Parameter passing of generator function

        function * gen(args){
            console.log(args) // 'aaa'
            let one = yield 111
            console.log(one) // 'bbb'
    
            let two = yield 222
            console.log(two) // 'ccc'
            
            let three = yield 333
            console.log(three)
        }
    
        // Execute the generator function to get the iterator object
        let iterator = gen('aaa')
    
        console.log(iterator.next()) // {value: 111, done: false}
        // The next method can pass in arguments, which will be used as the result returned after the previous yield
        console.log(iterator.next('bbb')) // {value: 222, done: false}
        console.log(iterator.next('ccc')) // {value: 333, done: false}
        console.log(iterator.next('ddd')) // {value: undefined, done: true}
    
  • Generator function instance 1:
    1s rear console output 111 -- > 2S rear console output 222 -- > 3S rear console output 333 = = > total time taken 6s

       // Asynchronous programming, such as file operation, network request, database operation
        // 1s rear console output 111 -- > 2S rear console output 222 -- > 3S rear console output 333 = = > total time taken 6s
    
        // Using 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)
            }, 3000)
        }
    
        function * gen(){
            yield one()
            yield two()
            yield three()
        }
    
        let iterator = gen()
        iterator.next()
        
    
        // The following is the regional approach
        // setTimeout(()=>{
        //     console.log(111)
        //     setTimeout(()=>{
        //         console.log(222)
        //         setTimeout(()=>{
        //             console.log(333)
        //         }, 3000)
        //     }, 2000)
        // }, 1000)
    
  • Generator function instance 2:
    Get order data -- > User simulation data

        // Simulate obtaining user data -- > order data -- > commodity data
        function getUsers(){
            setTimeout(()=>{
                let data = 'user data'
                iterator.next(data) // It is equivalent to sending the obtained data back to users
            }, 1000)
        }
    
        function getOrders(){
            setTimeout(()=>{
                let data = 'Order data'
                iterator.next(data)
            }, 2000)
        }
    
        function getGoods(){
            setTimeout(()=>{
                let data = 'Commodity data'
                iterator.next(data)
            },3000)
        }
    
        // Define generator functions
        function * gen (){
            let users = yield getUsers()
            console.log(users) // user data
    
            let orders = yield getOrders()
            console.log(orders) // Order data
    
            let goods = yield getGoods()
            console.log(goods) // Commodity data
        }
    
        // Call the generator function to get the iterator object
        let iterator = gen()
        iterator.next()
    

12.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

  1. Promise constructor: Promise(excutor) {}
  2. Promise.prototype.then method
  3. Promise.prototype.catch method

Basic use

        // Instantiate Promise object
        const p = new Promise(function(resolve, reject){
            setTimeout(()=>{
                let data = 'User data in database'
                // resolve(data)
                let err = 'Data reading failed'
                reject(err)
            },1000)
        })

        p.then((value)=>{
            console.log('enter success')
            console.log(value)
        },err=>{
            console.log('enter failed')
            console.log(err)
        })

Promise encapsulates read files

// 1. Introduce fs module fileSystem file system
const fs = require('fs')

// 2. Call the method to read the file
// fs. Readfile ('. / resource / file. MD', (err, data) = > {/ / data is a buffer used to store binary files. Its usage is similar to that of an array
//     //If it fails, an error is thrown
//     if(err) throw err
//     //If successful, read the file
//     console.log(data.toString())
// })

// 3. Use promise package
const p = new Promise(function(resolve, reject){
    fs.readFile('./resource/file.md', (err,data)=>{
        if(err){
            reject(err)
        }else{
            resolve(data.toString())
        }
    })
})
p.then((value)=>{
    console.log(value)
},(reason)=>{
    console.error(reason)
})

Promise encapsulates ajax

        // Interface address: https://api.apiopen.top/getJoke
        // Native ajax send request
        // // 1. create object
        // const xhr = new XMLHttpRequest()

        // // 2. initialization
        // xhr.open('GET', 'https://api.apiopen.top/getJoke')

        // // 3. send out
        // xhr.send()

        // // 4. Binding event
        // xhr.onreadystatechange = function(){
        //     //Judgment stage
        //     if(xhr.readyState === 4 ){
        //         //Judgment response status code
        //         if(xhr.status >= 200 && xhr.status < 300){
        //             //If the status code is success, print the returned result
        //             console.log(xhr.response)
        //         }else{
        //             //If it fails
        //             console.error(xhr.status)
        //         }
        //     }
        // }


        // promise encapsulates sending ajax requests
        const p = new Promise((resolve, reject)=>{
            const xhr = new XMLHttpRequest()
            xhr.open('GET', 'https://api.apiopen.top/getJoke')
            xhr.send()
            xhr.onreadystatechange = function(){
                if(xhr.readyState === 4){
                    if(xhr.status >=200 && xhr.status < 300){
                        resolve(xhr.response)
                    }else{
                        reject(xhr.status)
                    }
                }
            }
        })
        p.then((value)=>{
            console.log(value)
        },(reason)=>{
            console.log(reason)
        })

Promise.prototype.then method

The return result of the then method is still a promise object. The success or failure of its state is determined by the execution result of the callback function in then

  • If the result returned in the callback function is a non promise attribute, the status is success, and the result of return is the value of resolve after the promise is successful
    Note: if there is no return, it will return undefined by default, so the status is still successful

  • If the returned result is a promise object, the state of the promise object is the state of the promise object returned by then

  • If a value is thrown (such as an error), the status is failed

        const p = new Promise((resolve, reject)=>{
            setTimeout(()=>{
                resolve('user data')
                // reject('something went wrong ')
            }, 1000)
        })
    
        const result = p.then((value)=>{ // After p executes resolve, the status is successful and the first function is executed
            console.log(value )
            // 1. Return non promise objects
            // return 233 // 233
            // 2. Return promise object
            return new Promise((resolve, reject)=>{
                resolve('ok') // Status is success, value = ok
                // reject('error!! '/ / the status is failed
    
            })
            // 3. Throw an error
            // throw new Error('error!!!')
        },(reason)=>{ // p after executing reject, the status is failed, and the second function is executed
            console.warn(reason)
        })
    
        // The return result of the then method is still a promise object. The success or failure of its state is determined by the execution result of the callback function in then
        console.log(result)
    

This feature of the then method determines that the then method can be called in a chain

        const p = new Promise((resolve, reject)=>{
            setTimeout(()=>{
                resolve('user data')
                // reject('something went wrong ')
            }, 1000)
        })

        // call chaining 
        p.then((value)={
            // ...
        }).then((value)=>{
            // ...
        })

Read files in order through chain call

	// 1. Introduce fs module fileSystem file system
	const fs = require('fs')
	
	// Use the traditional way to read file 1 = > read file 2 = > read file 3
	// fs.readFile('./resource/file1.md', (err, data)=>{
	//     let data1 = data.toString()
	//     fs.readFile('./resource/file2.md', (err,data)=>{
	//         let data2 = data.toString()
	//         fs.readFile('./resource/file3.md', (err,data)=>{
	//             let data3 = data.toString()
	//             let data_all = {data1,data2,data3}
	//             console.log(data_all)
	//         })
	//     })
	// })
	
	// Use promise to read file 1 = > read file 2 = > read file 3
	const p = new Promise((resolve, reject)=>{
	    fs.readFile('./resource/file1.md', (err,data)=>{
	        resolve(data)
	    })
	})
	
	p.then((value) => {
	    return new Promise((resolve, reject)=>{
	        fs.readFile('./resource/file2.md',(err,data)=>{
	            let data_all =  {
	                data1: value.toString(),
	                data2: data.toString()
	            }
	            resolve(data_all)
	        })
	    })
	}).then((value)=>{
	    return new Promise((resolve,reject)=>{
	        fs.readFile('./resource/file3.md', (err,data)=>{
	            value.data3 = data.toString()
	            resolve(value)
	        })
	    })
	}).then(value=>{
	    console.log(value)
	    //  {data1: '# this is file 1', data2: '# this is file 2', data3: '# this is file 3'}
	})

Promise object catch method

Callback used to specify the failure of the promise object

        const p = new Promise((resolve,reject)=>{
            setTimeout(()=>{
                // Failed to set the status of the p object to
                reject('opps error')
            },1000)
        })

        // p.then((value)=>{}, (reason)=>{
        //     console.error(reason)
        // })
        
        // It is equivalent to the second callback function in then
        p.catch((reason)=>{
            console.warn(reason)
        })

13.set

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

  • size, returns the number of elements in the collection

  • Add, add a new element and return the current collection

  • Delete, delete element, return Boolean value

  • has, which detects whether the collection contains an element and returns a Boolean value

        let s = new Set(['sound of wind','sound of rain','Reading sound','sound of wind']) // It can accept iteratable data, which is generally passed into the array
        // 'the sound of the rain ',' the sound of the wind ','
    
        let size = s.size // View the number of elements
        let has = s.has('Reading sound') // Detect whether the element is true
        s.add('Underwater sound') // Add element
        s.delete('Reading sound') // Delete element
        let has2 = s.has('Reading sound') // Detect whether the element is false
        
        // Traversal set
        for(let item of s){
            console.log(item)
        }
        s.clear() // Empty collection
    
        console.log(s, has,has2, typeof s)
    

Application of set

Array de duplication

        let arr = [1, 2, 3, 4, 5, 4, 3, 2, 1]
        // Array de duplication
        let result = [...new Set(arr)]
        console.log(result) // [1, 2, 3, 4, 5]

Find intersection

        let arr = [1, 2, 3, 4, 5, 4, 3, 2, 1]
        let arr2 = [4, 5, 6, 5, 6]

        // Find intersection
        let result = [...new Set(arr)].filter(item => { // The arr is de duplicated and traversed
            let s2 = new Set(arr2) // Change arr2 to a collection of non repeating elements
            if(s2.has(item)){ // If the element exists in s2
                return true
            }else{
                return false
            }

        })
        console.log(result) // [4, 5]

        // Simplified writing
        let result2 = [...new Set(arr)].filter(item => new Set(arr2).has(item))
        console.log(result2)

Union set

        let arr = [1, 2, 3, 4, 5, 4, 3, 2, 1]
        let arr2 = [4, 5, 6, 5, 6]

        // Union set: connect two arrays = > Convert to a set with no duplicate elements = > Convert to an array
        let union = [...new Set([...arr, ...arr2])]
        console.log(union)
        // [1, 2, 3, 4, 5, 6]

Difference set

        let arr = [1, 2, 3, 4, 5, 4, 3, 2, 1]
        let arr2 = [4, 5, 6, 5, 6]

        // Find the difference set - arr find the difference set of arr2, that is, find the elements in arr but not in arr2, which is equivalent to the inverse operation of finding the intersection
        let diff = [...new Set(arr)].filter(item => !(new Set(arr2).has(item)))
        console.log(diff) // [1, 2, 3]

14.Map

ES6 provides a map data structure. It is similar to an object and a collection of key value pairs, but the range 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 "extension operator" and for Of for traversal
Properties and methods of Map:

  • size, returns the number of Map elements

  • set, add a new element and return the current Map

  • get, return the key value of the key name object

  • has, which detects whether the Map contains an element and returns a Boolean value

  • Clear, clear the collection and return undefined

        // Declare Map
        let m = new Map()
    
        // Add element
        m.set('name','LiMing') // Key name
        m.set('tell',function(){
            console.log('I am LiMing ')
        })
        let friend = {
            school: 'Third middle school'
        }
        m.set(friend,['Xiao Wu','Xiao Wang','Xiao Fang'])
    
        // Delete element
        m.delete('tell')
    
        // Get element
        let friends = m.get(friend)
        console.log(friends)
    
        // Get the number of elements
        let size = m.size
        console.log(size)
    
        // Traverse Map
        for(let item of m){
            console.log('item---',item)
            // Each item is an array. The first element is a key and the second element is a value
        }
        
        // Empty Map
        m.clear()
        console.log(m)
        console.log(typeof m)
    

class

Keywords: Front-end git github Vue.js html

Added by twigletmac on Sat, 05 Mar 2022 22:12:50 +0200