当前位置: 首页 > backend >正文

ECMAScript2020(ES11)新特性

概述

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类型

BigIntES2020引入的新的数值类型,用于表示任意精度的整数,解决了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.仅当左侧值为nullundefined时,才会返回右侧值。
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 || "无数据"); // "无数据"(误判)
兼容性
  • 可选链运算符?.
  1. 可选链运算符?.用于安全地访问对象的属性,避免出现TypeError错误。
  2. 当属性不存在时,返回undefined,而不是抛出错误。
  3. 支持属性访问(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
兼容性
http://www.xdnf.cn/news/16643.html

相关文章:

  • Apache HTTP Server 2.4.50 路径穿越漏洞(CVE-2021-42013)
  • 【LangChain4j 详解】Java生态大语言模型框架设计哲学与架构原理
  • Python多线程利器:重入锁(RLock)详解——原理、实战与避坑指南
  • 【硬件-笔试面试题】硬件/电子工程师,笔试面试题-50,(知识点:TCP/IP 模型)
  • electron开发桌面应用入门
  • Web UI自动化测试之PO篇
  • 【刷题】东方博宜oj 1307 - 数的计数
  • 域名https证书
  • 关于mysql时间类型和java model的日期类型映射
  • anaconda和Miniconda安装包32位64位皆可,anaconda和Miniconda有什么区别?
  • 超宽带测距+测角+无线通信一体化跟随模组:机械狗、无人车、无人机等跟随
  • 02 NameServer是如何管理Broker集群的
  • 16-C语言:第17天笔记
  • NET Framewor组件安装(附下载安装教程)
  • Java面试宝典:MySQL InnoDB引擎底层解析
  • c#_文件的读写 IO
  • 【lucene】使用docvalues的案例
  • AR技术赋能航空维修:精度与效率的飞跃
  • 2025年数学与应用物理国际会议(ICMAP 2025)
  • FFmpeg:因码流采集与封装不同步导致录制出来的MP4文件会出现黑屏、绿屏的问题
  • 服务器安全防护指南:原理剖析与实战对策
  • mac升级安装python3
  • ubuntu编译opendds
  • day25——HTML CSS 前端开发
  • 一款基于 ReactNative 最新发布的`Android/iOS` 新架构文档预览开源库
  • 【AI 数据管理】Text2SQL:当AI成为你和数据库之间的金牌“翻译官”
  • 如何将JPG、PNG、GIF图像转换成PDF、SVG、EPS矢量图像
  • rabbitmq--默认模式(点对点)
  • 应用药品 GMP 证书识别技术,实现证书信息的自动化、精准化提取与核验
  • 【动态规划算法】斐波那契数列模型