ES11(ES2020)新特性

文章类型:Javascript

发布者:hp

发布时间:2025-03-08

一:属性

1:动态导入 (Dynamic Import):使用import()函数实现动态加载模块。

const modulePath = './module.js';  
import(modulePath).then(module => {  
  module.doSomething();  
});  

2:可选链 (Optional Chaining) ?.:安全地访问嵌套对象属性。

const user = { profile: { name: 'Alice' } };  
console.log(user?.profile?.age); // undefined(不报错) 

3:空值合并运算符 (Nullish Coalescing) ??:处理null或undefined默认值。

const value = null ?? 'default'; // 'default'  



4:全局This:globalThis 提供跨环境的全局对象访问。

console.log(globalThis === window); // 浏览器中为 true  

5:BigInt:表示任意精度整数的基本数据类型,适用于超大数值计算

const bigNum = 9007199254740991n;  
console.log(bigNum + 1n); // 9007199254740992n  

6:Promise.allSettled():在所有Promise完成后(无论成功或失败)获取结果。

const promises = [Promise.resolve(1), Promise.reject('error')];  
Promise.allSettled(promises).then(results => {  
  results.forEach(({ status, value, reason }) => {  
    console.log(status); // 'fulfilled' 或 'rejected'  
  });  
});  

7:String.prototype.matchAll():返回正则匹配的所有结果及捕获组信息(返回迭代器)‌

const regex = /t(e)(st)/g;  
const str = 'test1test2';  
Array.from(str.matchAll(regex), match => match); // ['test', 'test']  

8:export * as:将模块所有导出内容聚合到命名空间对象中‌

// module.js  
export const a = 1;  
export function b() {}  
// main.js  
export * as utils from './module.js';  

二:总结

‌1:异步控制‌:Promise.allSettled() 适用于需要完整跟踪多个异步操作的场景(如批量请求监控)‌

2:安全访问对象‌:可选链操作符简化深层嵌套对象属性访问‌

3‌:大数运算‌:BigInt 解决金融、科学计算中的精度问题‌