在每一年的年底,ECMA 都会发布一份新的 ECMAScript 规范(简称为 ES)。2020 年的 ES11,也称为 ES2020,在语言层面上带来了很多新的特性,这篇文章就来介绍一下 ES11 的新特性。
BigInt
BigInt 类型是目前为止 ES 中最大的整数类型,它可以支持任意大小的整数,也可以在数字后面加 n 来声明 BigInt。
const a = 9007199254740990n; const b = 1n; console.log(a + b); // 9007199254740991n
Promise.allSettled
Promise.allSettled 方法可以用来处理多个异步操作,相当于 Promise.all 方法,但是它无论每个 Promise 对象的状态如何,都会等到所有异步操作都完成后才会返回结果。
-- -------------------- ---- ------- ----- -------- - ------------------- ----- -------- - --- ----------------- ------- -- ------------------- ---- -------- -- ----- -------- - --- ----------------- ------- -- ------------------ ---- -------- -- ----------------------------- --------- ------------------------- -- -------------------- -- -- -- ------- ------------ ------ - -- -- - ------- ------------ ------ ------- -- -- - ------- ----------- ------- ------- --展开代码
String.prototype.matchAll
String.prototype.matchAll 方法可以用来在字符串中查找所有匹配的正则表达式,返回一个迭代器对象。
-- -------------------- ---- ------- ----- ----- - ----------------- ----- ------ - ------------------ ----- ------- - ---------------------------- ------------------------ -- --------- ---- ------ ---- ------ -- ------ ------------------ ------- ---------- ------------------------ -- --------- ---- ------ ---- ------ -- ------ ------------------ ------- ---------- ------------------------ -- --------- ---- ------ ---- ------ --- ------ ------------------ ------- ----------展开代码
import()
import() 方法可以像函数一样动态加载模块,可以异步加载模块,还可以在运行时根据需要动态加载模块。
async function loadModule(moduleName) { const module = await import(`./modules/${moduleName}.js`); return module; } loadModule("module1").then((module) => console.log(module));
globalThis
globalThis 表示全局对象,可以在任何地方访问它,不管当前代码运行在哪个作用域内,都可以使用 globalThis 来访问全局对象。
// 全局环境下 console.log(globalThis === window); // true // 在 Web Worker 中 console.log(globalThis === self); // true // 在 Node.js 中 console.log(globalThis === global); // true
可选链操作符
可选链操作符(?.)可以用来判断一个属性或方法是否存在,如果存在,则执行它,否则返回 undefined。
-- -------------------- ---- ------- ----- ---- - - ----- ----- ----- -------- - ----- ---- ------ ------ ----- -- -- --------------------------------- -- ---- ----- ------------------------------------ -- --------- -------------------------------- -- ---------展开代码
空值合并操作符
空值合并操作符(??)可以用来判断一个值是否为 null 或 undefined,如果是,则返回默认值。
let name = null; let age; console.log(name ?? "unknown"); // "unknown" console.log(age ?? 18); // 18 console.log(null || "unknown"); // "unknown" console.log(undefined || 18); // 18
以上是 ES11 的新特性,通过学习这些新特性,可以让我们的代码更加简洁、高效。建议大家在实际开发中尽量使用最新的 ECMAScript 规范,让我们的代码更加优雅。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67c92c18e46428fe9e04006d