ES7、ES8、ES9、ES10新特性大盤點

  • ES7

    • Array.prototype.includes()方法

      之前:indexOf() find() findIndex()

    • 求冪運算符**

      代替 Math.pow()

  • ES8

    • Async/Await

      使用同步代碼實現異步訪問資源的能力

    • Object.values(),Object.entries()

      遍歷對象,供 for…of 使用

    • String padding

      String.padStart(目標字符串的長度,[需要向前補充的字符串])

      String.padEnd(目標字符串的長度,[需要向後補充的字符串])

      "12".padStart(10, "YYYY-MM-DD"); // "YYYY-MM-12"
      "09-12".padStart(10, "YYYY-MM-DD"); // "YYYY-09-12"
      "x".padEnd(5, "ab"); // 'xabab'
      
    • Object.getOwnPropertyDescriptors()

      目的: 解決 Object.assign()無法正確拷貝 get 屬性和 set 屬性的問題

      現象:

      source 對象的 foo 屬性的值是一個賦值函數,Object.assign 方法將這個屬性拷貝給 target1 對象,結果該屬性的值變成了 undefined

      const source = {
        set foo(value) {
          console.log(value);
        },
        get bar() {
          return "浪裏行舟";
        }
      };
      const target1 = {};
      Object.assign(target1, source);
      console.log(Object.getOwnPropertyDescriptor(target1, "foo")); // value: undefined
      

      原因: Object.assign 方法總是拷貝一個屬性的值,而不會拷貝它背後的賦值方法或取值方法。

      解決:

      使用Object.getOwnPropertyDescriptors()方法配合Object.defineProperties()方法,實現正確拷貝

             const source = {
             set foo (value) {
                 console.log(value)
             },
             get bar () {
                 return '浪裏行舟'
             }
             }
             const target2 = {}
             Object.defineProperties(target2, Object.getOwnPropertyDescriptors(source))
             console.log(Object.getOwnPropertyDescriptor(target2, 'foo')) // set f foo(value)
         ```
      
      
  • ES9

    • for await of

      目的:解決 for of 方法能夠遍歷具有 Symbol.iterator 接口的同步迭代器數據,但是不能遍歷異步迭代器的問題

      for await of 用來遍歷具有 Symbol.asyncIterator 方法的數據結構

      • for of 遍歷:

        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 (let item of arr) {
            console.log(Date.now(), item.then(console.log));
          }
        }
        test();
        

        結果:

        1576048278664 Promise {<pending>}
        1576048278665 Promise {<pending>}
        1576048278665 Promise {<pending>}
        Promise {<resolved>: undefined}
        100
        2000
        3000
        
      • for await of 遍歷

        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();
        

        結果:

        Promise {<pending>}
        1576048386487 2000
        1576048386487 100
        1576048387487 3000
        

      使用 for await of 遍歷時,會等待前一個 Promise 對象的狀態改變後,再遍歷到下一個成員。

      • Object Rest Spread

        spread 操作符 功能:複製、合併、拆解

        const arr1 = [10, 20, 30];
        const copy = [...arr1]; // 複製
        console.log(copy); // [10, 20, 30]
        const arr2 = [40, 50];
        const merge = [...arr1, ...arr2]; // 合併
        console.log(merge); // [10, 20, 30, 40, 50]
        console.log(Math.max(...arr)); // 30 拆解
        
        • 擴展運算符拷貝一個對象(類似這樣 obj2 = {…obj1}),實際只是一個對象的淺拷貝。

          const input = {
            a: 1,
            b: 2
          };
          const output = {
            ...input,
            c: 3
          };
          input.a = "浪裏行舟";
          console.log(input, output); // {a: "浪裏行舟", b: 2} {a: 1, b: 2, c: 3}
          
        • 如果屬性的值是一個對象的話,該對象的引用會被拷貝

          const obj = { x: { y: 10 } };
          const copy1 = { ...obj };
          const copy2 = { ...obj };
          obj.x.y = "浪裏行舟";
          console.log(copy1, copy2); // x: {y: "浪裏行舟"} x: {y: "浪裏行舟"}
          console.log(copy1.x === copy2.x); // → true
          
        • Object rest rest 屬性必須始終出現在對象的末尾

        const input = {
          a: 1,
          b: 2,
          c: 3
        };
        let { a, ...rest } = input;
        console.log(a, rest); // 1 {b: 2, c: 3}
        
    • Promise.prototype.finally()

      Promise.prototype.finally() 方法返回一個 Promise,在 promise 執行結束時,無論結果是 fulfilled 或者是 rejected,在執行 then()和 catch()後,都會執行 finally 指定的回調函數。

      目的:避免同樣的語句需要在 then()和 catch()中各寫一次的情況。

  • ES10

    • Array.prototype.flat()

      數組扁平化 newArray = arr.flat(depth) depth:要提取的嵌套數組的結構深度

    • Array.prototype.flatMap()

      只能打平一層

      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]
      
    • Object.fromEntries()

      Object.entries 將對象轉換成數組

      Object.fromEntries 將數組轉換成對象

      • ES10 之前
      const obj = {
        a: 21,
        b: 22,
        c: 23
      };
      console.log(Object.entries(obj)); // [['a',21],["b", 22],["c", 23]]
      let arr = Object.entries(obj).filter(([a, b]) => b > 21); // [["b", 22],["c", 23]]
      let obj1 = {};
      for (let [name, age] of arr) {
        obj1[name] = age;
      }
      console.log(obj1); // {b: 22, c: 23}
      
      • 有了 Object.fromEntries()
      const obj = {
        a: 21,
        b: 22,
        c: 23
      };
      console.log(Object.entries(obj)); // [['a',21],["b", 22],["c", 23]]
      let obj1 = Object.fromEntries(
        Object.entries(obj).filter(([a, b]) => b > 21)
      );
      console.log(obj1); // {b: 22, c: 23}
      
    • String.trimStart 和 String.trimEnd

      移除開頭和結尾的空格

    • String.prototype.matchAll

      應用:一個正則表達式在字符串裏面有多個匹配

      通過 ES9 的 String.prototype.matchAll 方法,可以一次性取出所有匹配。

      function collectGroup1(regExp, str) {
        let results = [];
        for (const match of str.matchAll(regExp)) {
          results.push(match[1]);
        }
        return results;
      }
      console.log(collectGroup1(/"([^"]*)"/g, `"foo" and "bar" and "baz"`));
      // ["foo", "bar", "baz"]
      
發佈了139 篇原創文章 · 獲贊 92 · 訪問量 19萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章