ECMAScript 2020(ES11)
2025-02-20 20:00
2025-02-22 20:45
核心特性
1. 可选链操作符(Optional Chaining ?.)
安全访问嵌套对象属性,避免因中间属性不存在而抛出错误,处理不确定结构的 API 响应或配置对象。
const user = { profile: { name: "星泪" } };
console.log(user?.profile?.age); // undefined(而非报错)
console.log(user?.address?.city?.trim()); // undefined(链式安全访问)
2. 空值合并运算符(Nullish Coalescing ??)
为变量提供默认值,仅当左侧为 null 或 undefined 时生效(区别于 || 的假值判断)。
const config = { timeout: 0, theme: null };
const timeout = config.timeout ?? 30; // 0(0 不是 null/undefined)
const theme = config.theme ?? "light"; // 'light'
3. 动态导入(Dynamic Import import())
按需异步加载模块(返回 Promise),适用于代码分割或条件加载
// 按需加载工具模块
if (userNeedsAnalytics) {
import("./analytics.js")
.then(module => module.init())
.catch(err => console.log("加载失败"));
}
4. BigInt 类型
BigInt
类型,表示任意精度的整数,解决 Number 类型精度限制(超过 2^53-1 的整数)。
const bigNum = 9007199254740993n;
console.log(bigNum + 1n); // 9007199254740994n
console.log(BigInt(Number.MAX_SAFE_INTEGER) + 2n); // 正确计算大数
5. Promise.allSettled()
等待所有 Promise 完成(无论成功或失败),返回结果数组描述每个 Promise 的状态,批量请求需汇总全部结果(如日志上报)。
const promises = [fetch("/api1"), fetch("/api2")];
Promise.allSettled(promises).then(results => {
results.forEach(result => {
if (result.status === "fulfilled") console.log(result.value);
else console.error(result.reason);
});
});
6. 全局对象 globalThis
统一不同环境(浏览器、Node.js、Web Worker)下的全局对象访问。
// 浏览器中:globalThis === window
// Node.js 中:globalThis === global
console.log(globalThis.setTimeout === window.setTimeout); // true(浏览器环境)
7. String.prototype.matchAll() 标准化
返回正则表达式匹配的所有结果及捕获组(ES10 中引入,ES11 正式标准化)
const str = "test1test2";
const matches = [...str.matchAll(/t(e)(st(\d?))/g)];
console.log(matches[0][1]); // 'e'(第一个捕获组)
总结
ECMAScript 2020(ES11)通过 可选链 和 空值合并 大幅提升了代码的健壮性与简洁性,解决了深层访问和默认值处理的痛点;动态导入 和 Promise.allSettled 优化了异步编程与资源加载;BigInt 和 globalThis 则填补了语言在数学计算和跨环境兼容性上的空白。这些特性广泛应用于现代前端框架(如 React/Vue 的按需加载)、Node.js 服务端开发及数据敏感型场景,标志着 JavaScript 向更安全、更高效的方向演进。后续版本(如 ES2021 的 Promise.any)继续深化了异步编程能力。
评论区
评论区寄了
文章目录
核心特性
1. 可选链操作符(Optional Chaining ?.)
2. 空值合并运算符(Nullish Coalescing ??)
3. 动态导入(Dynamic Import import())
4. BigInt 类型
5. Promise.allSettled()
6. 全局对象 globalThis
7. String.prototype.matchAll() 标准化
总结