ES11新增的9個新特性


本Ecma標准定義了ECMAScript 2020語言。它是ECMAScript語言規范的第11版。自從1997年第一版出版以來,ECMAScript已經發展成為世界上使用最廣泛的通用編程語言之一。它被稱為嵌入在web瀏覽器中的語言,但也被廣泛應用於服務器和嵌入式應用程序。

那么ES11又引入了那些新特性呢?

1. String 的 matchAll 方法

2. 動態導入語句 import()

3. import.meta

4. export * as ns from 'module'

5. Promise.allSettled

6. 新增數據類型: BigInt

7. 頂層對象: globalThis

8. 空值合並運算符: ??

9. 可選鏈操作符:?.

一、matchAll

matchAll() 方法返回一個包含所有匹配正則表達式的結果的迭代器。可以使用 for...of 遍歷,或者使用 展開運算符(...) 或者 Array.from 轉換為數組.

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

const matchs = str.matchAll(regexp);
console.log(matchs); // RegExpStringIterator {}
console.log([...matchs])
/*
0: (4) ["test1", "e", "st1", "1", index: 0, input: "test1test2", groups: undefined]
1: (4) ["test2", "e", "st2", "2", index: 5, input: "test1test2", groups: undefined]
length: 2
/*

RegExp.exec()  和 matchAll() 區別:

在 matchAll 出現之前,通過在循環中調用 regexp.exec() 來獲取所有匹配項信息。

const regexp = RegExp('foo[a-z]*','g');
const str = 'table football, foosball';
let match;

while ((match = regexp.exec(str)) !== null) {
  console.log(`Found ${match[0]} start=${match.index} end=${regexp.lastIndex}.`);
}
// expected output: "Found football start=6 end=14."
// expected output: "Found foosball start=16 end=24."

如果使用 matchAll ,就可以不必使用 while 循環加 exec 方式

const regexp = RegExp('foo[a-z]*','g');
const str = 'table football, foosball';
const matches = str.matchAll(regexp);

for (const match of matches) {
  console.log(`Found ${match[0]} start=${match.index} end=${match.index + match[0].length}.`);
}
// expected output: "Found football start=6 end=14."
// expected output: "Found foosball start=16 end=24."

二、import()

import 標准的用法是導入的木塊是靜態的,會使所有被帶入的模塊在加載時就別編譯,無法做到按需加載編譯,降低了首頁的加載速度。在某些場景中,你可能希望根據條件導入模塊,或者按需導入模塊,這是就可以使用動態導入代替靜態導入了

在import() 之前,我們需要更具條件導入模塊時只能使用 require() 

if (xx) {
  const module = require('/module')  
}

// 現在可以這么寫
if (xx) {
  const module = import('/module')
}

@babel/preset-env 已經包含了 @babel/plugin-syntax-dynamic-import,因此如果要使用 import() 語法,只需要配置 @babel/preset-env 即可。

另外:import() 返回的是一個Promise 對象:

// module.js
export default {
  name: 'shenjp'
}

// index.js
if (true) {
  let module = import('./module.js');
  console.log(module); // Promise {<pending>
  module.then(data => console.log(data)); // Module {default: {name: "shenjp"}, __esModule: true, Symbol(Symbol.toStringTag): "Module"}
}

三、import.meta

import.meta對象是由ECMAScript實現的,它帶有一個null的原型對象。這個對象可以擴展,並且它的屬性都是可寫,可配置和可枚舉的。

<script type="module" src="my-module.mjs"></script>
console.log(import.meta); // { url: "file:///home/user/my-module.mjs" }

因為 import.meta 必須要在模塊內部使用,如果不加 type="module",控制台會報錯:Cannot use 'import.meta' outside a module。

在項目中需要下載 @open-wc/webpack-import-meta-loader  才能正常使用。

module: {
    rules: [
        {
            test: /\.js$/,
            use: [
                require.resolve('@open-wc/webpack-import-meta-loader'),
                {
                    loader: 'babel-loader',
                    options: {
                        presets: [
                            "@babel/preset-env",
                            "@babel/preset-react"
                        ]
                    },
                }
            ]
        }
    ]
}

效果如下:

//src/index.js
import React from 'react';
console.log(import.meta);//{index.js:38 {url: "http://127.0.0.1:3000/src/index.js"}}

四、export * as ns from 'module'

ES2020新增了 export * as XX from 'module',和 import * as XX from 'module'

// module.js
export * as ns from './info.js'

可以理解為下面兩條語句的合並:

import * as ns from './info.js';
export { ns };

需要注意的是:export * as ns from 'module' 並不會真的導入模塊,因此在該模塊中無法使用 ns。

五、Promise.allSettled

Promise.allSettled()方法返回一個在所有給定的promise都已經fulfilled或rejected后的promise,並帶有一個對象數組,每個對象表示對應的promise結果。

當您有多個彼此不依賴的異步任務成功完成時,或者您總是想知道每個promise的結果時,通常使用它。

想比較之下, Promise.all() 更適合做相互依賴的Promise,只要有一個失敗就結束

const promise1 = Promise.resolve(100);
const promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, 'info'));
const promise3 = new Promise((resolve, reject) => setTimeout(resolve, 200, 'name'))

Promise.allSettled([promise1, promise2, promise3]).
    then((results) => console.log(result));
/* 
    [
        { status: 'fulfilled', value: 100 },
        { status: 'rejected', reason: 'info' },
        { status: 'fulfilled', value: 'name' }
    ]
*/

可以看出,Promise.allSettled() 成功之后返回的也是一個數組,但是改數組的每一項都是一個對象,每個對象都有一個status屬性,值為 fulfilled 和 rejected .

如果status是 fulfilled,那么改對象的另一個屬性是 value ,對應的是該Promise成功后的結果。

如果status是 rejected,那么對象的另一個屬性是 reason,對應的是該Promise失敗的原因。

六、BigInt

BigInt 是一種數字類型的數據,它可以表示任意精度格式的整數。在此之前,JS 中安全的最大數字是 9009199254740991,即2^53-1,在控制台中輸入 Number.MAX_SAFE_INTEGER 即可查看。超過這個值,JS 沒有辦法精確表示。另外,大於或等於2的1024次方的數值,JS 無法表示,會返回 Infinity。

BigInt 即解決了這兩個問題。BigInt 只用來表示整數,沒有位數的限制,任何位數的整數都可以精確表示。為了和 Number 類型進行區分,BigInt 類型的數據必須添加后綴 n.

//Number類型在超過9009199254740991后,計算結果即出現問題
const num1 = 90091992547409910;
console.log(num1 + 1); //90091992547409900

//BigInt 計算結果正確
const num2 = 90091992547409910n;
console.log(num2 + 1n); //90091992547409911n

我們還可以使用 BigInt 對象來初始化 BigInt 實例:

console.log(BigInt(999)); // 999n 注意:沒有 new 關鍵字!!!

需要說明的是,BigInt 和 Number 是兩種數據類型,不能直接進行四則運算,不過可以進行比較操作。

console.log(99n == 99); //true
console.log(99n === 99); //false 
console.log(99n + 1);//TypeError: Cannot mix BigInt and other types, use explicit conversionss

七、GlobalThis

JS 中存在一個頂層對象,但是,頂層對象在各種實現里是不統一的。

從不同的 JavaScript 環境中獲取全局對象需要不同的語句。在 Web 中,可以通過 window、self 取到全局對象,但是在 Web Workers 中,只有 self 可以。在 Node.js 中,它們都無法獲取,必須使用 global。

var getGlobal = function () {
    if (typeof self !== 'undefined') { return self; }
    if (typeof window !== 'undefined') { return window; }
    if (typeof global !== 'undefined') { return global; }
    throw new Error('unable to locate global object');
};

ES2020 中引入 globalThis 作為頂層對象,在任何環境下,都可以簡單的通過 globalThis 拿到頂層對象。

八、空值合並運算符

ES2020 新增了一個運算符 ??。當左側的操作數為 null 或者 undefined時,返回其右側操作數,否則返回左側操作數。

在之前我們經常會使用 || 操作符,但是使用 || 操作符,當左側的操作數為 0 、 null、 undefined、 NaN、 false、 '' 時,都會使用右側的操作數。如果使用 || 來為某些變量設置默認值,可能會遇到意料之外的行為。

?? 操作符可以規避以上問題,它只有在左操作數是 null 或者是 undefined 時,才會返回右側操作數。

const someValue = 0;
const defaultValue = 100;
let value = someValue ?? defaultValue; // someValue 為 0 ,value 的值是 0

九、可選鏈操作符

可選鏈操作符 ?. 允許讀取位於連接對象鏈深處的屬性的值,而不必明確驗證鏈中的每個引用是否有效。?. 操作符的功能類似於 . 鏈式操作符,不同之處在於,在引用為空(nullish, 即 null 或者 undefined) 的情況下不會引起錯誤,該表達式短路返回值是 undefined。

例如,我們要訪問 info 對象的 animal 的 reptile 的 tortoise。但是我們不確定 animal, reptile 是否存在,因此我們需要這樣寫:

const tortoise = info.animal && info.animal.reptile && info.animal.reptile.tortoise;

因為 null.reptile 或  undefined.reptile 會拋出錯誤:TypeError: Cannot read property 'reptile' of undefined 或 TypeError: Cannot read property 'reptile' of null,為了避免報錯,如果我們需要訪問的屬性更深,那么這個這句代碼會越來越長。

有了可選鏈之后我們就可以簡化:

const tortoise = info.animal?.reptile?.tortoise;

可以看到可選鏈操作符 ?. 和空位合並操作符一樣,都是針對的 null 和 undefined 這兩個值。

參考:

ecma-262

import.meta

Promise.allSettled

GlobalThis

Nullish coalescing operator

Optional chaining operator

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM