概述
ECMAScript2020于2020年6月正式發布, 本文會介紹ECMAScript2020(ES11),即ECMAScript的第11個版本的新特性。
以下摘自官網:ecma-262
ECMAScript 2020, the 11th edition, introduced the matchAll method for Strings, to produce an iterator for all match objects generated by a global regular expression; import(), a syntax to asynchronously import Modules with a dynamic specifier; BigInt, a new number primitive for working with arbitrary precision integers; Promise.allSettled, a new Promise combinator that does not short-circuit; globalThis, a universal way to access the global this value; dedicated export * as ns from ‘module’ syntax for use within modules; increased standardization of for-in enumeration order; import.meta, a host-populated object available in Modules that may contain contextual information about the Module; as well as adding two new syntax features to improve working with “nullish” values (undefined or null): nullish coalescing, a value selection operator; and optional chaining, a property access and function invocation operator that short-circuits if the value to access/invoke is nullish.
ECMAScript2020(ES11)
ES2020
的新特性如下:
- 動態導入 (
Dynamic Import
) BigInt
大整數類型Promise.allSettled
String.matchAll
globalThis
import.meta
- 模塊命名空間導出
for-in
循環枚舉標準化- 其它
動態導入 import
語法
ES2020
增強了import
語法,用于動態導入模塊,允許在運行時按需導入,返回一個Promise
,適用于懶加載。
// 傳統靜態導入(必須位于文件頂部)
// import { sum } from './math.js';// 動態導入(按需加載)
async function loadMathModule() {const mathModule = await import('./math.js');console.log(mathModule.sum(1, 2)); // 3
}// 條件加載示例
if (needFeatureX) {import('./feature-x.js').then(module => {module.init();});
}
兼容性

大數運算 BigInt
類型
BigInt
是ES2020
引入的新的數值類型,用于表示任意精度的整數,解決了Number
類型無法處理超出2^53-1
的數值問題。通過在數字末尾添加n
或者調用BigInt()
函數創建。
// 創建 BigInt
const maxSafeInt = Number.MAX_SAFE_INTEGER; // 9007199254740991
const bigInt1 = 9007199254740992n; // 直接加 n
const bigInt2 = BigInt(9007199254740992); // 函數轉換// 大數運算
console.log(bigInt1 + 1n); // 9007199254740993n
console.log(bigInt1 * 2n); // 18014398509481984n// 注意:BigInt 不能與 Number 直接運算
// console.log(bigInt1 + 1); // 錯誤!TypeError
console.log(bigInt1 + BigInt(1)); // 正確
兼容性

Promise.allSettled
方法
Promise.allSettled
方法接收一個Promise
數組,返回一個新的Promise
,該Promise
在所有輸入的Promise
都已完成(無論成功或失敗)后,才會完成。
const promises = [Promise.resolve(1),Promise.reject('Error'),Promise.resolve(3)
];Promise.allSettled(promises).then(results => {console.log(results);// [// { status: 'fulfilled', value: 1 },// { status: 'rejected', reason: 'Error' },// { status: 'fulfilled', value: 3 }// ]});
兼容性

字符串 matchAll
方法
matchAll
方法返回一個迭代器,包含所有匹配正則表達式的結果,每個結果都是一個數組,包含匹配的字符串和捕獲組。
const str = "Hello world, hello ES2020!";
const regex = /hello (\w+)/gi;// 使用 matchAll 獲取所有匹配結果(包括捕獲組)
const matches = str.matchAll(regex);for (const match of matches) {console.log(`匹配內容: ${match[0]}`); // 完整匹配console.log(`捕獲組: ${match[1]}`); // 第一個捕獲組console.log(`索引位置: ${match.index}`);
}
匹配內容: Hello world
捕獲組: world
索引位置: 0
匹配內容: hello ES2020
捕獲組: ES2020
索引位置: 13
兼容性

全局對象 globalThis
globalThis
是統一返回全局對象的方式,瀏覽器window
、Node.jsglobal
、Web Workerself
等都可以通過globalThis
訪問。
// 舊環境檢測全局對象的方式(繁瑣且不統一)
const globalObj = typeof window !== 'undefined' ? window :typeof global !== 'undefined' ? global :self;// 新方式(統一且簡潔)
console.log(globalThis === window); // 瀏覽器環境中為 true
console.log(globalThis === global); // Node.js 環境中為 true
兼容性

模塊元數據 import.meta
import.meta
提供了關于當前模塊的元數據信息,例如模塊的 URL、導入的依賴等,具體內容由宿主環境決定;且其僅在模塊type='module'
中可用。
// 在瀏覽器環境中
console.log(import.meta.url);
// 輸出當前模塊的 URL,如 "http://example.com/main.js"// 在 Vite 等構建工具中
console.log(import.meta.env.MODE);
// 輸出當前環境模式(如 "development" 或 "production")
兼容性

模塊命名空間導出
export * as namespace
語法可以簡化模塊重新導出,允許將一個模塊的所有導出內容聚合到一個命名空間對象中導出。等同于先導入再導出,但沒有中間變量
// 舊寫法
import * as utils from './utils.js';
export { utils };// 新寫法(一行搞定)
export * as utils from './utils.js';
兼容性

for-in
枚舉順序標準化
ES2020
明確規定for-in
循環遍歷對象屬性的順序:
- 數字鍵(按升序排列)
- 字符串鍵(按添加順序排列)
Symbol
鍵(按添加順序排列)
const obj = { b: 2, 1: 100, a: 1 };
obj[3] = 300;for (const key in obj) {console.log(key); // 輸出順序:1 → 3 → b → a
}
其它
ES2020
對空值處理也進行了更新,如下:
- 空值合并運算符
??
1.僅當左側值為null
或undefined
時,才會返回右側值。
2.解決了邏輯或運算符||
會誤判0
、''
、false
等假值的問題
const name = null;
const displayName = name ?? "匿名用戶";
console.log(displayName); // "匿名用戶"const count = 0;
const displayCount = count ?? "無數據";
console.log(displayCount); // 0(而非 "無數據")// 對比 || 的區別
console.log(count || "無數據"); // "無數據"(誤判)
兼容性

- 可選鏈運算符
?.
- 可選鏈運算符
?.
用于安全地訪問對象的屬性,避免出現TypeError
錯誤。 - 當屬性不存在時,返回
undefined
,而不是拋出錯誤。 - 支持屬性訪問(
obj?.prop
)、方法調用(obj?.method()
)和數組索引(obj?.array[index]
)
const user = {profile: {name: "Alice",address: {city: "Beijing"}}
};// 舊寫法(繁瑣)
const city = user && user.profile && user.profile.address && user.profile.address.city;// 新寫法(簡潔)
const city2 = user?.profile?.address?.city;
console.log(city2); // "Beijing"// 安全調用可能不存在的方法
user.profile.getAge?.(); // 若方法不存在,返回 undefined 而非報錯// 安全訪問可能不存在的數組索引
const arr = null;
console.log(arr?.[0]); // undefinedjs
兼容性
