ES7 - 11新特性總結

es7

  1 Array.prototype.includes  之前都是使用indexOf判斷,沒有返回-1,現在includes更加方便

    Includes  方法用來檢測數組中是否包含某個元素,返回boolean值

    let arr = [1, 2, 3, 4, 5];

    arr.includes(1);// true

    arr.includes(6);// false

  2 指數操作符 **,用來實現冪運算,功能與 Math.pow 結果相同

    2 ** 10;// 2 的 10 次方,與 Math.pow(2, 10); 結果相同,都是 1024

es8

  async 和 await  這兩種語法結合,可以讓非同步程式碼像同步程式碼一樣

    async 是 非同步 的簡寫,await 可以認為是 async wait 的簡寫,await 理解為等待一個非同步方法執行完成

   1 async 函數的返回值為 promise 對象

    promise 對象的結果是由 async 函數執行的返回值決定

    // 方法前面加上一個 async ,就變成了一個async函數了,
    // 只要返回值不是一個promise對象,返回值就是一個成功的promise對象,參考promise
    // 返回的是一個promise對象,該promise返回成功,則async函數返回成功,該promise返回失敗,則async返回失敗
    async function fn(){
      // return '晚上要學習';
      return new Promise((resolve, reject)=>{
        resolve('成功');
        // reject('失敗');
      })
    }
    const result = fn();
    console.log(result);// 可以看到返回值是要給promise對象
    result.then(value =>{
      console.log('返回成功');
    }, reason =>{
      console.log('返回失敗');
    })

   2 await 表達式

    await 必須寫在 async 函數中

 

    await 右側的表達式一般為 promise 對象

    await 返回的是 promise 成功的值

    await 的 promise 失敗了,就會拋出異常,需要通過 try...catch 捕獲處理

    // 創建一個 promise 對象
    const p = new Promise((resolve, reject) =>{
      // resolve('成功');
      reject('失敗');
    })
    // await 要放在 async 中
    async function fn(){
      try{
        let result = await p;// await 返回結果就是 promise 對象返回成功的值
        console.log(result);// 成功
      } catch (e) {// 在 catch 中可以獲取promise對象狀態為失敗的值
        console.log(e);// 失敗
      }
    }
    fn();// 調用函數

   3 async 和 await 結合 在 vue 中結合 axios 使用(非同步請求同步化)

    1. 在不同情況下發送請求,做相同的處理

    export default{
      name: 'test',
      data(){
        return {
          tableData: []
        }
      },
      created() {
        this.getTableData();
      },
      methods: {
        handleSearch(){// 在create 中的請求結果和在這個方法中的處理結果相同
          this.getTableData();
        },
        async getTableData(){
          try {
            let res = await axios.get(url)
            this.tableData = res.data;
          } catch (err) {
            console.log('請求出錯');
          }
        }
      }
    }

    2.在不容情況下的請求,做不同的處理

    export default{
      name: 'test',
      data(){
        return {
          tableData: []
        }
      },
      async created() {
        try{
          let res = await this.getTableData();
          this.tableData = res.data;
        }catch(err){
          console.log('請求出錯');
        }
      },
      methods: {
        async handleSearch(){
          try {
            let res = await this.getTableData();
            this.tableData = res.data;
          } catch(err) {
            console.log('請求出錯');
          }
          this.getTableData();
        },
        getTableData(){
          return new Promise((resolve, reject) =>{
            axios.get(url);
          }).then(res=>{
            resolve(res);
          }).catch(err=>{
            reject(err);
          })
        }
      }
    }

  對象方法的擴展

    Object.values()  返回一個給定對象的所有可枚舉屬性值的數組

    Object.entries()  返回一個給定對象自身可遍歷屬性 [key, value] 的數組

    Object.getOwnPropertyDescriptors()  返回指定對象所有自身屬性的描述對象

    const p = {
      LPL: '我們是冠軍',
      RNG: ['UZI', 'Letme', 'xiaohu', 'MLXG', 'Ming']
    }
    Object.keys(p);// ['LPL','RNG'] 返回key數組
    Object.values(p);// ['我們是冠軍', ['UZI', 'Letme', 'xiaohu', 'MLXG', 'Ming']]  返回值對應的數組
    Object.entries(p);// [['LPL', '我們是冠軍'],['RNG', ['UZI', 'Letme', 'xiaohu', 'MLXG', 'Ming']]]  返回值是一個數組,每個元素也都是一個數組
    Object.getOwnPropertyDescriptors(p);// 返回結果是對象,對象中還是對象,還有別的值,列印看一下

 es9

  擴展運算符與 rest 參數

    rest 參數與擴展運算符在 es6 中已經引入了,不過 es6 中只是針對數組,對象不行

    在 es9 中為對象提供了像數組一樣的 rest 參數和擴展運算符,注意rest參數後面不允許有其他參數

// 使用 rest 參數操作對象,user 是後面沒有聲明的對象, 注意rest參數後面不能有其他參數
function connect({ RNG, adc, ...user }) {
  console.log(RNG);// 全華班
  console.log(adc);// UZI
  console.log(user);// {UZI: '簡自豪', MLXG: '劉世宇'}
}
connect({
  RNG: '全華班',
  adc: 'UZI',
  UZI: '簡自豪',
  MLXG: '劉世宇'
})
const ONE = { q: '天音波' }, TEO = { w: '金鐘罩' }, THREE = { e: '天雷破' }, FOUR = { r: '猛龍擺尾' };
const MLXG = { ...ONE, ...TEO, ...THREE, ...FOUR };
console.log(MLXG);// {q: "天音波", w: "金鐘罩", e: "天雷破", r: "猛龍擺尾"}

   

es10

  對象的擴展方法Object.fromEntries()  參數是一個二維數組,或者是一個 Map

const rng = Object.fromEntries([['adc', 'UZI'], ['uzi', '簡自豪']]);// 這裡是二維數組,數組裡面套數組
console.log(rng);// {adc: "UZI", uzi: "簡自豪"}

const map = new Map();
map.set('adc', 'uzi');
const uzi = Object.fromEntries(map);// 這裡是 map 集合,這裡查看es8中的Object.entries()方法
console.log(uzi);// {adc: "uzi"}

  字元串方法擴展 trimStart 和 trimEnd

    trim 是清空字元串兩端空格,trimStart 則是清除開始空格,trimEnd 清除結束空格

  數組方法擴展 flat 與 flatMap

    flat 將數組維度降低,多維數組轉換成低維數組

const arr = [1, 2, 5, [6, 7, [8, 9]]];
// 參數是一個數字,表示深度,三維數組變成一維數組,深度為2
console.log(arr.flat(2));// [1, 2, 5, 6, 7, 8, 9]
console.log(arr.flat());// [1, 2, 5, 6, 7, [8, 9]]

const arr1 = [1, 2, 3];
const result = arr1.map(i => i * 10);// [10, 20, 30]
const result1 = arr1.map(i => i * 10);// [[10], [20], [30]]
const result11 = arr1.flatMap(i => i * 10);// [10, 20, 30] // 只是這一個功能,降低數組維度

   Symbol 擴展 

   Symbol.prototype.description

let zn = Symbol('張寧');
console.log(zn.description);// 輸出字元串 張寧

 

es11

  私有屬性,聲明的標誌是一個#

    class Persion{
            // 公有屬性
            name;
            // 私有屬性,#為私有屬性的標誌
            #age;
            #weight;
            constructor(name, age, weight){
                this.name = name;
                this.#age = age;
                this.#weight = weight;
            }
            // 類裡面的方法
            say(){
                console.log(this.name);
                console.log(this.#age);
                console.log(this.#weight);
            }
        }
        const boy = new Persion('張寧', 24, '80kg');
        console.log(boy);// Persion {name: "張寧", #age: 24, #weight: "80kg"}
        console.log(boy.name);// 張寧
        console.log(boy.#age);// Private field '#age' must be declared in an enclosing class
        console.log(boy.#weight);// 提示私有屬性,只能出現在類裡面
        boy.say();// 依次輸出 張寧 24 80kg

   Promist.allSettled() 方法

// 聲明兩個promise對象
const p1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('成功1');
    // reject('失敗1');
  }, 1000)
});
const p2 = new Promise((resolve, reject) => {
  setTimeout(() => {
    // resolve('成功2');
    reject('失敗2');
  }, 1000)
});

// 兩個都成功才會返回成功, 返回數據一個是狀態 resolve,
// 一個是值,存在數組中 [{status: "fulfilled", value: "成功1"},{status: "fulfilled", value: "成功2"}],fulfilled表示成功
// 當p2返回錯誤的時候,result依然返回成功,Promise.allSettled 總是返回成功,
// 當p2返回錯誤的時候,返回數據一個是狀態 resolve,
// 一個是值 [{status: "fulfilled", value: "成功1"},{status: "rejected"reason: "失敗2"]
const result = Promise.allSettled([p1, p2]);
// 兩個都成功才會返回成功, 返回數據一個是狀態 resolve,一個是值在數組中 ['成功1', '成功2']
// 有一個返回失敗,就是失敗,返回數據一個是狀態 rejected,一個是錯誤的值 失敗1
const res = Promise.all([p1, p2]);
console.log(result);
console.log(res);

   字元串擴展  String.prototype.matchAll()

    通過正則表達式獲取想要得到的欄位

  可選鏈操作符  ?.  判斷?前面的值有沒有傳入,如果傳遞了,就去讀取後面的屬性,沒有傳遞就返回 undefined

function main(config) {
  // 當main傳遞數據的時候,返回 uzi
  console.log(config.rng.adc);
}
main({rng:{adc: 'uzi'}});// main 中傳遞數據的時候返回 uzi
main();// 什麼都不傳遞的時候報錯 Cannot read property 'rng' of undefined

function main1(config) { console.log(config?.rng?.adc); } main1({rng:{adc: 'uzi'}});// main 中傳遞數據的時候返回 uzi main1();// 什麼都不傳遞的時候,返回undefined

   動態 import  就是按需載入,懶載入

  BigInt 類型

// BigInt 類型  大整型
let n = 510n;
console.log(n, typeof(n));// 510n bigint

let nn = 123;
console.log(BigInt(nn));// 輸出 123n  BigInt函數中只能是整數,不能是浮點類型的數

// 大整型主要應用於大數值的運算
let max = Number.MAX_SAFE_INTEGER;// 最大整數
console.log(max);// 9007199254740991
console.log(max + 1);// 9007199254740992
console.log(max + 1);// 9007199254740992  已經不能加上去了
// 可以通過大整型進行計算相加,大整型不能直接與int進行計算,都是大整型才能進行計算
console.log(BigInt(max));// 9007199254740991n
console.log(BigInt(max) + BigInt(1));// 9007199254740992n
console.log(BigInt(max) + BigInt(6));// 9007199254740997n

  絕對全局對象 globalThis

    之前在javascript在不同環境獲取全局對象有不同的方式

      node 中 通過 global 

      web 中通過 window,self

    現在 globalThis 提供了一個標準的方式來獲取不同環境下的全局 this 對象。

    不像 window 或者 self 這些屬性,它確保可以在有無窗口的各種環境下正常工作。

    所以,可以放心使用 globalThis,不用擔心它的運行環境。全局作用域中的 this 就是globalThis

 

Tags: