ES 新特性合集

101 阅读3分钟
安装 检查检测当前Node.js对ES的支持情况
npm install -g es-checker

\

ES7 (ES2016):

\

  1. Array.prototype.includes()
   [1, 2, 3].includes(2);     // true
   [1, 2, 3].includes(4);     // false
   [1, 2, 3].includes(3, 3);  // false
   [1, 2, 3].includes(3, -1); // true
   [1, 2, NaN].includes(NaN); // true

\

ES8 (ES2017): 

   

     1.async function fun (){

       try {

              let res =await axios({url:'xxxx'})

              console.log(res)

              let res2 =await axios({url:'xxxx'})

              console.log(res2)

           }catch (err) {

             console.error(err)

           }

      }

\

    2.  Object.values

      旧的写法:

    let obj = {a: 1, b: 2, c: 3}
    Object.keys(obj).forEach((key, index)=>{
    console.log(key, obj[key])
    })

    新写法:
    let obj = {a: 1, b: 2, c: 3}
    Object.values(obj).forEach(value=>console.log(value)) // 1, 2, 3

    或者

     let obj = {a: 1, b: 2, c: 3}
     for (let value of Object.values(obj)) {
     console.log(value)
   }
   // 1, 2, 3

ES9 (ES2018):

     1.  

   for-of是用来遍历同步操作的
for-of里面用await,如果有其他操作,也会有输出顺序错误
for await of 是可以对异步集合进行操作

    旧:

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

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

  test()
  // 1597047404040 Promise {<pending>}
  // 1597047404040 Promise {<pending>}
  // 1597047404040 Promise {<pending>}
  // 1000
  // 2000
  // 3000

   新:

         function Gen (time){

               return new Promise(function (resolve, reject){

               setTimeout(function (){

                  resolve(time)

               }, time)

         })

      }

      async function test (){

         let arr = [Gen(2000), Gen(100), Gen(3000)]

          for await (let item of arr) {

            console.log(Date.now(), item)

            }

         }

      test()

    // 1575536194608 2000

   // 1575536194608 100

   // 1575536195608 3000

\

   2. Promise.prototype.finally()

axios({url: 'xxxx'})

.then((response) => {

console.log(response.status);

}).catch((error) => {

console.log(error);

}).finally(() => {

document.querySelector('#spinner').style.display ='none';

});

\

ES10 (ES2019):  

       1. Array.prototype.flat()  多维数组是一种常见的数据格式,特别是在进行数据检索的时候。将多维数组打平是个常见的需求。通常我们能够实现,但是不够优雅。

const numbers1 = [1,2, [3,4, [5,6]]]

console.log(numbers1.flat()) // [1, 2, 3, 4, [5, 6]]

2.Array.prototype.flatMap()  方法首先使用映射函数映射每个元素,然后将结果压缩成一个新数组。从方法的名字上也可以看出来它包含两部分功能一个是 map,一个是 flat(深度为 1)。

let arr = [1,2,3]

console.log(arr.map(item => [item *2]).flat())    // [2, 4, 6]

console.log(arr.flatMap(item => [item *2]))    // [2, 4, 6] flat && map

3. 这里 err 是必须的参数,在 ES10 可以省略这个参数:

        try {

console.log('Foobar')

}catch {

console.error('Bar')

}

        

ES 2020:

   Promise.allSettled方法接收一组 Promise,并且会返回所有的结果 - 而不管是 resolved 还是 rejected。在之前,这是不可能的,尽管有些类似的实现比如:raceall。它只会“运行所有的 promise - 而不关心它们的结果”

\

2.动态引入

\

Javascript 的动态引入,允许你把 JS 文件作为一个模块动态的引入到你的应用中。这就像你使用 webpack 和 Babel 一样。这个功能可以帮助你处理按需加载的代码,拆分代码,而且,并不需要 webpack 或者其它模块处理器。如果,你喜欢也可以在 if-else 块中加载代码。在 if-else 块中引入一个模块,这样的好处是:不会污染全局命名空间

\

       preview

\

ES 2021:

         1.

             旧写法: a = a || '默认值';

              新写法: a||= '默认值';

\

// 或赋值运算符
x ||= y
// 等同于
x || (x = y)


// 与赋值运算符
x &&= y
// 等同于
x && (x = y)


// Null 赋值运算符
x ??= y
// 等同于
x ?? (x = y)

\

2.replaceAll

旧:

'aabbcc'.replace('b', '_')
// 'aa_bcc'

\

正则

'aabbcc'.replace(/b/g, '_')
// 'aa__cc' 

\

新: 'aabbcc'.replaceAll('b', '_')
// 'aa__cc'

\

3.  Promise.any() 接收一个Promise可迭代对象,只要其中的一个 promise 成功,就返回那个已经成功的 promise 。如果可迭代对象中没有一个 promise 成功(即所有的 promises 都失败/拒绝),就返回一个失败的 promise

const p = Promise.any([p1, p2, p3]);

const promise1 = new Promise((resolve, reject) => reject('我是失败的Promise_1'));
const promise2 = new Promise((resolve, reject) => reject('我是失败的Promise_2'));
const promiseList = [promise1, promise2];
Promise.any(promiseList)
.then(values=>{
console.log(values);
})
.catch(e=>{
console.log(e);
});

\

文章: www.jianshu.com/p/41fd1fccf…