Summary of ES6, ES7, ES8, ES9, ES10, ES11, ES12 knowledge points

Foreword: ES6 has been used by everyone at work, so the knowledge points of ES6 will not be introduced in detail, let's learn the knowledge points of ES7 --- ES12 together! Four red, red, red for the gold, three and silver in the next year! ! !

Table of contents

1. ES6

2. ES2016 (ES7)

   1. Array.prototype.includes()  

   1.2 Syntax and examples 

    1.3 Notes

    2. The exponentiation operator**

     2.1 Syntax and examples

     2.2 Points to note

3. ES2017 (ES8)

    3. Object.values()

    4. Object.entries()

    5. Object.getOwnPropertyDescriptors()

  6. String.prototype.padStart

        6.1 Grammar                

        6.2 Examples

        6.3 Application scenarios

    7. String.prototype.padEnd

   8. async/await  

        8.1 Grammar

        8.2 Usage Scenarios

        8.3 Notes

        8.4 The pitfalls of async/await            

4. ES2018 (ES9)

    9. Object Rest & Spread

        9.1 Grammar

        9.2 Notes

    10. for await of

         10.1 We know that for...of runs synchronously, see the following code

    10.2 ES9 can use the syntax of for...await...of to operate 

    11. Promise.prototype.finally()

        11.1 Syntax        

        11.2 Usage Scenarios

5. ES2019 (ES10)

    12. Object.fromEntries()

        12.1 Example 1: Object conversion operation                 

        12.2 Example 2: Map to Object        

        12.3 Example 3: Filtering   

    13. Array.prototype.flat()

        13.1 Syntax         

        13.2  Demo

    14. Array.prototype.flatMap()

    15. String.prototype.trimStart()

    16. Symbol.prototype.description

    17. JSON.stringify() enhancements

    18. Revised Function.prototype.toString()

6. ES2020 (ES11)

   19. Nullish coalescing Operator

    20. Optional chain Optional chaining          

       20.1 Grammar       

          20.2 Notes 

    21. BigInt

        21.1 Use method 1: add n after the number                

        21.2 Use method 2: use BigInt function                

        21.3 Operation

         21.4 Notes

    22. String.prototype.matchAll()

    23. Promise.allSettled()

7. ES2021 (ES12)

    25. Logical operators and assignment expressions (&&=, ||=, ??=)

         25.1  &&=

         25.2  ||=

         25.3  ??= 

    26. String.prototype.replaceAll()

    27. Number separator

    28. Promise.any


1. ES6

        ① let const :  Click here for details

        ② Arrow function  

        ③ Array destructuring assignment

        ④ template string

        ⑤ Generator and Iterator: Click here for details

        ⑥ promise: Click here for details

        ⑦ for..in  和 for...of 

        ES6 is not too much detailed introduction, compared to everyone has already used it very proficiently! ! !

2. ES2016 (ES7)

   1. Array.prototype.includes()  

 The includes( ) method is used to determine whether an array contains a specified value, and returns true if it does, otherwise returns false.

   1.2 Syntax and Examples 

const arr = ['Barry','Lishen','Jenny','Chany'];

arr.includes(value,index)

     value, the element value to be looked up. index Optional, start searching at index  index value . If negative, the search starts at the index of arr.length + index in ascending order . The default is 0.

const arr = ['Barry', 'Lishen', 'Jenny', 'Chany'];

console.log(arr.includes('Barry')); // true
console.log(arr.includes('Barry',0)); // true
console.log(arr.includes('Barry',1)); // false
console.log(arr.includes('Barry',2)); // false
console.log(arr.includes('Barry',-1)); // false
console.log(arr.includes('Barry',-2)); // false

数组的长度是 4
index 是 -5
computed index 是 4 + (-5) = -1
如果计算出的索引小于 0,则整个数组都会被搜索。 所以下面为 true

console.log(arr.includes('Barry',-5)); // true

Computed index is less than 0

If index is negative, the calculated index will be used as the starting position to search for value . If the calculated index is less than 0, the entire array is searched.

    1.3 Notes

        ①The  search  includes()string is case-sensitive.        

    const arr = ['Barry', 'Lishen', 'Jenny', 'Chany'];

    console.log(arr.includes("BARRY")); // fasle

        ②  includes()Only simple types of data can be judged. For complex types of data, such as arrays of object types and two-dimensional arrays, these cannot be judged.

    const arr = ['Barry', 'Chany', ['EricNg', 'Tiny'], { name: 'Barry' }];

    console.log(arr.includes(['EricNg', 'Tiny'])); // fasle
    console.log(arr.includes({ name: 'Barry' })); // fasle

         ③ Can recognize NaN, indexOf cannot recognize NaN

    const arr = ['Barry', 'Lishen', 'Jenny', NaN, 'Chany'];

    console.log(arr.includes(NaN)); // true
    console.log(arr.indexOf(NaN)); // -1

Finally, if you just want to know whether a value exists in the array, but don't care about its index position, it is recommended to use includes(). If you want to get the position of a value in the array, then use the indexOf method. 

    2. The exponentiation operator**

     2.1 Syntax and examples

        Math.pow( )        

console.log(Math.pow(2, 10)); // 1024

        exponentiation operator**

console.log(2 ** 4); // 1024

        basic exponentiation 

    console.log(2 ** 3); // 8
    console.log(3 ** 2); // 9
    console.log(3 ** 2.5); // 15.588457268119896
    console.log(10 ** -1); // 0.1
    console.log(NaN ** 4); // NaN

     2.2 Points to note

         Spaces cannot appear between the two * signs of the exponentiation operator, otherwise a syntax error will be reported.

        

3. ES2017 (ES8)

    3. Object.values()

        Object.values The method returns an array whose members are the key values ​​of all enumerable properties of the parameter object itself (not inherited).

    const obj = {
      name: "Barry",
      age: 18,
      height: 185,
      money: 1000000000
    }
    console.log(Object.values(obj)); // ['Barry', 18, 185, 1000000000]

    4. Object.entries()

        The Object.entries() method returns an array whose members are key-value pairs of all traversable properties of the parameter object itself (excluding inherited ones).        

    const obj = {
      name: "Barry",
      age: 18,
      height: 185,
      money: 1000000000
    }
    console.log(Object.entries(obj)); // [['name','Barry'], ['age',18], ['height',185], ['money',100000000]]
    console.log(Object.entries([1, 2, 3])); // [['0',1], ['1',2], ['2',3]]

    5. Object.getOwnPropertyDescriptors()

        Object.getOwnPropertyDescriptors()  method is used to get descriptors of all of an object's own properties.

    const obj = {
      name: "Barry",
      age: 18,
    }

    const description = Object.getOwnPropertyDescriptors(obj);
    console.log(description)
    打印结果
    {
      age: {
        configurable: true
        enumerable: true
        value: 18
        writable: true
      }
      name: {
        configurable: true
        enumerable: true
        value: "Barry"
        writable: true
      }
    }

   In the above printed result

  • valueIndicates the default value for the current object

  • writableIndicates whether object properties can be modified

  • enumerableIndicates whether the current property can appear in the enumeration property of the object

  • configurableIndicates whether the properties of the current object can be deleted with delete

        How do we set and modify the properties of these objects, we can use es5 Object.defineProperty() 

    const obj = {
    }

    Object.defineProperty(obj, 'name', {
      value: "Barry",
      writable: true,
      enumerable: true,
      configurable: true
    });

    Object.defineProperty(obj, 'age', {
      value: 18,
      writable: true,
      enumerable: true,
      configurable: true
    })

    console.log(obj) // {name: 'Barry', age: 18}

        Next, let's demonstrate the situation where some properties are set to false:

                We can see that setting writable: false and configurable: false , when it is false, the value of the name object of the object cannot be changed or deleted , and the original object is still printed out.

    const obj = {
    }

    Object.defineProperty(obj, 'name', {
      value: "Barry",
      writable: false,
      enumerable: false,
      configurable: true
    });

    console.log(obj) // {name: 'Barry'}
    obj.name = 'lishen';
    console.log(obj); // {name: 'Barry'}
    delete obj.name
    console.log(obj); // {name: 'Barry'}

         When setting enumerable to false:

                When enumerable: false is set, it means that the properties of the object cannot be enumerated. At this time, the print object is empty, and the key of the traversal object is also empty.

    const obj = {
    }

    Object.defineProperty(obj, 'name', {
      value: "Barry",
      writable: true,
      enumerable: true,
      configurable: false
    });

    console.log(obj) // {}
    for (let key in obj) {
      console.log(key); // ""
    }

  6. String.prototype.padStart

        6.1 Grammar                

   str.padStart(targetLength , padString)

  • targetLength

        The target length to which the current string needs to be padded. If this number is less than the length of the current string, the current string itself is returned.

  • padString optional

        padding string. If the string is so long that the length of the padded string exceeds the target length, only the leftmost part will be kept and the rest will be truncated. The default value of this parameter is " "

        6.2 Examples

    const str = "ABC";

    console.log(str.padStart(10))  // "       ABC"
    console.log(str.padStart(10, 'foo')) // "foofoofABC"
    console.log(str.padStart(6, '123456')) // "123ABC"
    console.log(str.padStart(8, '0')) // "00000ABC"
    console.log(str.padStart(1)) // "ABC"

        6.3 Application scenarios

                Date formatting: format of yyyy-mm-dd:

    const now = new Date();
    const year = now.getFullYear();

    const mounth = (now.getMonth() + 1).toString().padStart(2, '0')
    const day = (now.getDate()).toString().padStart(2, '0')

    console.log(`${year}-${mounth}-${day}`); // 今天的日期 : 2021-01-27

               Number replacement (mobile phone number, bank card number, etc.)

    const tel = '18737740333';

    function formatTel (tel) {
      return tel.slice(-4).padStart(tel.length, '*')
    }

    console.log(formatTel(tel));  // *******0333

    7. String.prototype.padEnd

        Pads the specified string to the end of the string and returns a new string. The syntax is the same as String.prototype.padStart

    const str = "ABC";

    console.log(str.padEnd(10)) // "ABC       "
    console.log(str.padEnd(10, 'foo')) // "ABCfoofoof"
    console.log(str.padEnd(6, '123456')) // "ABC123"
    console.log(str.padEnd(1))  // "ABC"

   8. async/await  

         We all know that using Promise can solve the problem of callback hell very well, but if the processing flow is more complicated, then the whole code will be full of then, the semantics are not obvious, and the code cannot express the execution flow well. What about a more elegant asynchronous way to promise? That's async/await! Let's unravel its mystery together!

        8.1 Grammar

               If await is used in the async function, the code here in await will become synchronous, which means that it will continue only after the execution of the Promise behind await is completed and the result is obtained. await is waiting. Take a look at the example below: 

    function timeout () {
      return new Promise(resolve => {
        setTimeout(() => {
          console.log(1);
          resolve()
        }, 1000);
      })
    }

    // 不加async和await是2、1   加了是1、2
    async function foo () {
      await timeout()
      console.log(2)
    }

    foo(); // 1, 2

        8.2 Usage Scenarios

                The logic of asynchronous processing is implemented using synchronous code, and it also supports try catch to catch exceptions. This feels like writing synchronous code, so it is very in line with human linear thinking.

    async function foo () {
      try {
        let response1 = await fetch('https://www.baidu.com/')
        console.log(response1)
        let response2 = await fetch('https://juejin.im/')
        console.log(response2)
      } catch (err) {
        console.error(err)
      }
    }
    foo()

        8.3 Notes

                ①  await can only be used inside the function marked with async , if used alone, it will trigger a Syntax error ;

                ②  Asynchronous operation is required after await , otherwise it is meaningless, and the Promise object behind await does not need to write then , because one of the functions of await is to obtain the parameters passed by the success status of the subsequent Promise object.

        8.4 The pitfalls of async/await            

      Async/await Making your code look synchronous, in a way, also makes it behave more synchronously. The keyword blocks the code after it until the promise is fulfilled, just like performing a synchronous operation. It does allow other tasks to continue running during this time, but your own code is blocked. await 

                This means that your code may slow down due to a large number awaitof promises being fulfilled one after another. Each awaitwill wait for the previous one to complete, and what you actually want is for all of these promises to start resolving at the same time (as we would async/awaitwhen we didn't use them). There is a pattern to alleviate this problem - start the objects at the same time by  Promise storing them in variables, then wait for them all to finish executing .

4. ES2018 (ES9)

    9. Object Rest & Spread

        9.1 Grammar

         This piece of code shows the spread syntax, which can expand the data of the input object to the output object. This function is very practical. It should be noted that if the same attribute name exists, only the last one will take effect .        

    const input = {
      a: 1,
      b: 2,
      c: 3
    }

    const output = {
      ...input,
      d: 4
    }

    console.log(output)  // {a: 1, b: 2, c: 3, d: 4}

        9.2 Notes

        If the property's value is an object, the reference to that object is copied instead of creating a new object.        

    const obj = { x: { y: 10 } };
    const copy1 = { ...obj };
    const copy2 = { ...obj };
    obj.x.y = "jimmy";
    console.log(copy1, copy2); // x: {y: "jimmy"} x: {y: "jimmy"}
    console.log(copy1.x === copy2.x); // → true

    10. for await of

           Asynchronous iterator (for-await-of): The loop waits for each Promise object to become resolved before entering the next step.

         10.1 We know that for...of runs synchronously, see the following code

    function timeout (time) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve(time)
        }, time)
      })
    }

    async function test () {
      let arr = [timeout(2000), timeout(1000), timeout(3000),]
      for (let item of arr) {
        console.log(Date.now(), item.then(console.log))
      }
    }

    test()

    10.2 ES9 can use the syntax of for...await...of to operate 

        The for await of loop waits for each Promise object to become resolved before proceeding to the next step. All printed results are 2000, 1000, 3000

    function timeout (time) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve(time)
        }, time)
      })
    }

    async function test () {
      let arr = [timeout(2000), timeout(1000), timeout(3000),]
      for await (let item of arr) {
        console.log(Date.now(), item.then(console.log))
      }
    }

    test()

    11. Promise.prototype.finally()

         The Promise.prototype.finally() method returns a Promise. At the end of the promise execution, no matter whether the result is fulfilled or rejected, after executing then() and catch(), the callback function specified by finally will be executed. This provides a way to specify the code that needs to be executed regardless of whether the result is fulfilled or rejected after the promise is executed, avoiding the situation where the same statement needs to be written once in then() and catch().

        11.1 Syntax        

    function test () {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve('success')
        }, 1000)
      })
    }
    
    test().then(res => {
      console.log(res);
    }).catch(err => {
      console.log(err);
    }).finally(() => {
      console.log('finally');
    })

        11.2 Usage Scenarios

                loadingClose

                Every time a request is sent, there will be a loading prompt. After the request is sent, the loading prompt box needs to be closed, otherwise the interface cannot be clicked. Regardless of whether the request succeeds or fails, this loading needs to be closed. At this time, it is appropriate to write the code to close the loading in finally

        

5. ES2019 (ES10)

    12. Object.fromEntries()

        The method Object.fromEntries() converts the list of key-value pairs into an object. This method is opposite to Object.entries(). 

        12.1 Example 1: Object conversion operation                 

const obj = {
    name: 'jimmy',
    age: 18
}
const entries = Object.entries(obj)
console.log(entries)
// [Array(2), Array(2)]

// ES10
const fromEntries = Object.fromEntries(entries)
console.log(fromEntries)
// {name: "jimmy", age: 18}

        12.2 Example 2: Map to Object        

    const map = new Map();
    map.set('name', 'Barry');
    map.set('age', 18)

    console.log(map); // Map(2) {'name' => 'Barry', 'age' => 18}

    const obj = Object.fromEntries(map)
    console.log(obj); // {name: 'Barry', age: 18}

        12.3 Example 3: Filtering   

    const course = {
      math: 80,
      english: 85,
      chinese: 90
    }

    const res = Object.entries(course).filter(([key, val]) => val > 80);
    console.log(res); // [ [ 'english', 85 ], [ 'chinese', 90 ] ]
    console.log(Object.fromEntries(res)); //{english: 85, chinese: 90}

    13. Array.prototype.flat()

        13.1 Syntax         

let newArray = arr.flat( depth )

        depth Optional, specifies the structure depth to extract nested arrays, the default value is 1. 

        13.2  Demo

    flat()  The method will recursively traverse the array according to a specified depth, and combine all the elements with the elements in the traversed sub-array to return a new array.

const arr1 = [0, 1, 2, [3, 4]];
console.log(arr1.flat());  //  [0, 1, 2, 3, 4]
const arr2 = [0, 1, 2, [[[3, 4]]]];
console.log(arr2.flat(2));  //  [0, 1, 2, [3, 4]]

//使用 Infinity,可展开任意深度的嵌套数组
var arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

// `flat()` 方法会移除数组中的空项:
var arr5 = [1, 2, , 4, 5];
arr5.flat(); // [1, 2, 4, 5]

    14. Array.prototype.flatMap()

        The flatMap() method first maps each element using the map function, then compresses the result into a new array. It can also be seen from the name of the method that it contains two functions, one is map and the other is flat (the depth is 1).        

const numbers = [1, 2, 3]
numbers.map(x => [x * 2]) // [[2], [4], [6]]
numbers.flatMap(x => [x * 2]) // [2, 4, 6]

      Compare the difference between map and flatMap

let arr = ['今天天气不错', '', '早上好']
arr.map(s => s.split(''))
// [["今", "天", "天", "气", "不", "错"],[""],["早", "上", "好"]]
arr.flatMap(s => s.split(''))
// ["今", "天", "天", "气", "不", "错", "", "早", "上", "好"]

    15. String.prototype.trimStart()

        The trimStart() method removes spaces from the beginning of the string, and trimLeft() is an alias for this method.    

        String.prototype.trimEnd(), will not be introduced, similar to the following;    

let str = '   foo  '
console.log(str.length) // 8
str = str.trimStart() // 或str.trimLeft()
console.log(str.length) // 5

        

    16. Symbol.prototype.description

         The description of Symbol is only stored internally  Description and is not directly exposed to the outside world. We can read this property only when calling Symbol's toString():        

    const name = Symbol('Barry')
    console.log(name); // Symbol(Barry) 
    console.log(name.toString()); // Symbol(Barry)

    console.log(name === 'Symbol(Barry)');  // false
    console.log(name.toString() === 'Symbol(Barry)'); // true

        The description of Symbol can now be obtained through the description method: 

    const name = Symbol('Barry')

    console.log(name.description); // 'Barry'
    name.description = "es2" // 只读属性 并不能修改描述符

    // 如果没有描述符 输入undefined
    const age = Symbol();
    console.log(age.description); // undefined

    17. JSON.stringify() enhancements

         JSON.stringify in ES10 fixes some out-of-range Unicode display errors. Because JSON is encoded into UTF-8, characters within 0xD800–0xDFFF will cause display errors because they cannot be encoded into UTF-8. In ES10, it will use escape characters to process these characters instead of encoding, so it will be displayed normally.

    \uD83D\uDE0E  emoji 多字节的一个字符
    console.log(JSON.stringify('\uD83D\uDE0E')) // 打印出笑脸

    如果我们只去其中的一部分  \uD83D 这其实是个无效的字符串
    之前的版本 ,这些字符将替换为特殊字符,而现在将未配对的代理代码点表示为JSON转义序列
    console.log(JSON.stringify('\uD83D')) // "\ud83d"

    18. Revised Function.prototype.toString()

The toString method         of the previous function came from Object.prototype.toString() , and now the Function.prototype.toString() method returns a string representing the source code of the current function. Previously only this function would be returned, without comments, whitespace, etc.          

    function foo () {
      // ES2019(ES10)
      console.log('ES2019(ES10)');
    }
    console.log(foo.toString());

6. ES2020 (ES11)

   19. Nullish coalescing Operator

         The null coalescing operator?? ) is a logical operator that returns its right operand when the left operand is  nullOR undefined, otherwise it returns the left operand.   

        Unlike the logical OR operator ( ||), the logical OR operator returns the right operand if the left operand is false. That said, if you use  || to set default values ​​for certain variables, you may experience unexpected behavior. For example, when it is a false value (eg '', 0, NaN,false ).    

    const name = "" ?? "Barry"
    const name2 = "" || "Barry"

    console.log(name); // ""
    console.log(name2); // "Barry"

    const age = 0 ?? 18;
    const age2 = 0 || 18;
    console.log(age); // 0
    console.log(age2); // 18

        

    20. Optional chain Optional chaining          

       20.1 Grammar       

                The optional chaining operator (  ) allows reading the value of a property located deep in a chain of connection objects without having to explicitly verify that each reference in the chain is valid.  The function of the operator is similar to   that of the chain operator, except that instead of causing an error if the reference is  or  , the expression short-circuits the return value is  . When used with a function call, returns if the given function does not exist  . ?.?..null undefined undefinedundefined

                The optional chaining operator will make expressions shorter and more concise when trying to access object properties that may not exist. The optional chaining operator is also helpful when exploring the contents of an object if you are not sure which properties must be present.        

    const user = {
      name: "Barry",
      age: 18,
      address: {
        street: '成华大道',
        getNum () {
          return '188号'
        }
      }
    }

        In the previous syntax, if you want to get deep properties or methods, you have to do a pre-check, otherwise it is easy to hit  this kind of error, which is very likely to make your entire application hang.  Uncaught TypeError: Cannot read property...

const street = user && user.address && user.address.street
const num = user && user.address && user.address.getNum && user.address.getNum()
console.log(street, num)

         Use optional chaining 

const street2 = user?.address?.street
const num2 = user?.address?.getNum?.()
console.log(street2, num2)

          20.2 Notes 

                Optional chaining cannot be used for assignment

let object = {};
object?.property = 1; // Uncaught SyntaxError: Invalid left-hand side in assignment

    21. BigInt

         BigInt is a built-in object that provides a method to represent  integers greater than . This was originally the largest number that could be represented in Javascript. Can represent arbitrarily large integers. 2的53次方 \- 1   Number BigInt 

        21.1 Use method 1: add n after the number                

const bigInt = 9007199254740993n
console.log(bigInt)
console.log(typeof bigInt) // bigint

// `BigInt` 和 [`Number`]不是严格相等的,但是宽松相等的。
console.log(1n == 1) // true
console.log(1n === 1) // false

// `Number` 和 `BigInt` 可以进行比较。
1n < 2 // ↪ true
2n > 1 // ↪ true

        21.2 Use method 2: use BigInt function                

const bigIntNum = BigInt(9007199254740993n)
console.log(bigIntNum)

        21.3 Operation

let number = BigInt(2);
let a = number + 2n; // 4n
let b = number * 10n; // 20n
let c = number - 10n; // -8n
console.log(a);
console.log(b);
console.log(c);

         21.4 Notes

        BigInt cannot be used in methods in   [  Math ] objects; it cannot be mixed with any [  Number ]  instance, and both must be converted to the same type. Be careful when converting to and from the two types, as BigInt variables Numbermay lose precision when converted to [ ] variables.

    22. String.prototype.matchAll()

         matchAll()  The method returns an iterator containing all the results matching the regular expression and grouping capture groups.

    const regexp = /t(e)(st(\d?))/g;
    const str = "test1test2"

    const arr = [...str.matchAll(regexp)]

    console.log(arr);

          

    23. Promise.allSettled()

         We all know that Promise.all() has the ability to execute asynchronous tasks concurrently. But its biggest problem is that if one of the tasks is abnormal (reject), all tasks will hang up, and Promise will directly enter the reject state.

        Scenario: There are now three requests on the page, each requesting different data. If one interface service is abnormal, the whole fails, and the data cannot be rendered

        We need a mechanism. If a task is normal or abnormal in a concurrent task, the corresponding status will be returned. This is the  Promise.allSettled role of        

    const promise1 = () => {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve('promise1')
        }, 3000)
      })
    }

    const promise2 = () => {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve('promise2')
        }, 1000)
      })
    }

    const promise3 = () => {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          reject('error promise3')
        }, 2000)
      })
    }

    //  Promise.all 会走到catch里面
    Promise.all([promise1(), promise2(), promise3()]).then(res => {
      console.log('all-res', res);
    }).catch(err => {
      console.log('all-err', err);
    })

    // Promise.allSettled 不管有没有错误,三个的状态都会返回
    Promise.allSettled([promise1(), promise2(), promise3()]).then(res => {
      console.log('allSettled-res', res);
    }).catch(err => {
      console.log('allSettled-err', err);
    })

         

7. ES2021 (ES12)

    25. Logical operators and assignment expressions (&&=, ||=, ??=)

         25.1  &&=

                Logical AND assignment  x &&= y is equivalent to:         

x && (x = y);

        The above means that x = y when x is true. Please see the following example for details: 

    let a = 1;
    let b = 0;

    a &&= 2;

    b &&= 2;

    console.log(a); // 2
    console.log(b); // 0

         25.2  ||=

                 The logical OR assignment ( x ||= y) operation only  assigns a value x if false . x ||= y Equivalent to: x || (x = y) ;

    const a = { duration: 50, title: "" }

    a.duration ||= 20;
    console.log(a.duration);  // 50

    a.title ||= "Barry"
    
    console.log(a);

 

         25.3  ??= 

                The logical null assignment operator ( ) assigns to it only if   it is  nullish[3] or  ). x ??= y xnull undefined

     x ??= y Equivalent to: x ?? (x = y);

const a = { duration: 50 };

a.duration ??= 10;
console.log(a.duration); // 50

a.speed ??= 25;
console.log(a.speed); // 25
function config(options) {
  options.duration ??= 100;
  options.speed ??= 25;
  return options;
}

config({ duration: 125 }); // { duration: 125, speed: 25 }
config({}); // { duration: 100, speed: 25 }

  

    26. String.prototype.replaceAll()

         replaceAll()  The method returns a new string, and all satisfied parts in the new string will be replaced. Can be a string or a  , can be a string or a function to be called on each match. pattern replacement pattern RegExpreplacement

        The original string remains unchanged.

    const str = 'aabbccdd';
    const newStr = str.replaceAll('b', '*')
    console.log(newStr); // 'aa**bbccdd'

        When using regular expressions to search for values, it must be global. 

'aabbcc'.replaceAll(/b/, '.');
TypeError: replaceAll must be called with a global RegExp

    27.  Number Separator

         In European and American languages, longer values ​​allow a separator (usually a comma) to be added every three digits to increase the readability of the value. For example, 1000 you can write 1,000.

   ES2021JavaScript is allowed to use underscores ( _) as delimiters for numeric values.        

let budget = 1_000_000_000_000;
budget === 10 ** 12 // true

        This numeric separator does not specify the number of intervals, that is, a separator can be added every three digits, or every digit, every two digits, or every four digits. 

123_00 === 12_300 // true

12345_00 === 123_4500 // true
12345_00 === 1_234_500 // true

        Decimal and scientific notation can also use numeric separators. 

// 小数
0.000_001

// 科学计数法
1e10_000

        There are several points to note when using numeric separators.

  • Cannot be placed at the front (leading) or last (trailing) of the value.

  • Two or more delimiters cannot be concatenated.

  • There cannot be separators before and after the decimal point.

  • In scientific notation, there can be no separators before eor Eafter exponents.

        The following writing methods will report errors.

// 全部报错
3_.141
3._141
1_e12
1e_12
123__456
_1464301
1464301_

    28. Promise.any

         The method accepts a set of Promise instances as parameters and wraps them into a new Promise instance to return.

    const promise1 = () => {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve('promise1')
        }, 3000);
      })
    }

    const promise2 = () => {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve('promise2')
        }, 2000);
      })
    }

    const promise3 = () => {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          reject('promise3 error')
        }, 1000);
      })
    }

    Promise.any([promise1(), promise2(), promise3(),]).then(res => {
       // 只要有一个请求成功 就会返回第一个请求成功的 
      console.log('res', res); // 会返回promise2
    }).catch(err => {
      console.log('err', err);
    })

         The wrapper instance becomes state whenever one of the argument instances becomes  state; the wrapper  fulfilled instance  fulfilled becomes state if all argument instances become  state.rejected rejected 

  Promise.any() It is very similar to  Promise.race() the method, only one difference is that it will not end  because a certain Promise becomes a state, it must wait until all the parameter Promises become a state. Promise.any()   rejected rejected 

Guess you like

Origin blog.csdn.net/weixin_56650035/article/details/122705897