ES2021 特性及简单示例
介绍
Promise.any
逻辑赋值运算符
数字分隔符
结论
介绍
ES2021 是 ECMAScript 对应 2021 年的版本。此版本包含的新功能不如 ES6(2015 年)那么多,但也包含了一些实用的功能。
本文通过简单的代码示例介绍了 ES2021 提供的功能。这样,您无需复杂的解释即可快速理解这些新功能。
当然,需要具备 JavaScript 的基础知识才能完全理解所介绍的最佳内容。
ES2021 中的新 JavaScript功能包括:
➡️ String.prototype.replaceAll
➡️ Promise.any
➡️ WeakRef
➡️ 逻辑赋值运算符
➡️ 数字分隔符
String.protype.replaceAll
目前,如果不使用全局正则表达式 (/regexp/g),就无法替换字符串中子字符串的所有实例。
const fruits = '🍎+🍐+🍓+';
const fruitsWithBanana = fruits.replace(/\+/g, '🍌');
console.log(fruitsWithBanana); //🍎🍌🍐🍌🍓🍌
String 原型中添加了新的 replaceAll 方法。
const fruits = '🍎+🍐+🍓+';
const fruitsWithBanana = fruits.replaceAll('+', '🍌');
console.log(fruitsWithBanana); //🍎🍌🍐🍌🍓🍌
Promise.any
Promise.any 会在其中一个 Promise 满足条件时立即发出信号。这与 Pormise.race 类似,不同之处在于,当其中一个 Promise 拒绝时,any 不会提前拒绝。
const myFetch = url => setTimeout(() => fetch(url), Math.floor(Math.random() * 3000));
const promises = [
myFetch('/endpoint-1'),
myFetch('/endpoint-2'),
myFetch('/endpoint-3'),
];
// Using .then .catch
Promise.any(promises) // Any of the promises was fulfilled.
.then(console.log) // e.g. '3'
.catch(console.error); //All of the promises were rejected.
// Using async-await
try {
const first = await Promise.any(promises); // Any of the promises was fulfilled.
console.log(first);
}catch (error) { // All of the promises were rejected
console.log(error);
}
弱引用
WeakRef 提案包含两个主要的新功能:
-
使用 WeakRef 类创建对对象的弱引用。
-
使用 FinalizationRegistry 类在对象被垃圾收集后运行用户定义的终结器。
这些接口可以独立使用,也可以一起使用,具体取决于用例
WeakRef 对象包含对某个对象的弱引用,该对象被称为其目标或引用对象。对某个对象的弱引用不会阻止该对象被垃圾回收器回收。
弱引用的主要用途是实现保存大对象的缓存或映射,在这种情况下,希望大对象不会仅仅因为出现在缓存或映射中而保持活动状态。
function toogle(element) {
**const weakElement = new WeakRef(element);**
let intervalId = null;
function toggle() {
**const el = weakElement.deref();**
if (!el) {
return clearInterval(intervalId);
}
const decoration = weakElement.style.textDecoration;
const style= decoration === 'none' ? 'underline' : 'none';
decoration = style;
}
intervalId = setInterval(toggle, 1000);
}
const element = document.getElementById("link");
toogle(element);
setTimeout(() => element.remove(), 10000);
FinalizationRegistry
提供了一种方法来请求在注册表中注册的对象被回收时调用清理回调(终结器) ()。garbage-collected
您registry
在回调中创建传递:
const registry = new FinalizationRegistry(heldValue => {
// ....
});
然后,register
通过调用注册方法,传入对象及其保存的值,您可以获得任何想要清理回调的对象:
registry.register(theObject, "some value");
逻辑赋值运算符
逻辑赋值运算符将逻辑运算符和赋值表达式组合在一起。新增了两个运算符:
- 或 或 等于。
- 且 且 等于。
// Or Or Equals
| a | b | a ||= b | a (after operation) |
| true | true | true | true |
| true | false | true | true |
| false | true | true | true |
| false | false | false | false |
a ||= b
// Equivalent to:
a || (a = b);
// And And Equals
| a | b | a ||= b | a (after operation) |
| true | true | true | true |
| true | false | false | false |
| false | true | false | false |
| false | false | false | false |
a &&= b
// Equivalent to:
a && (a = b);
数字分隔符
此功能允许使用数字组之间的视觉分隔使数字文字更具可读性。
使用下划线(_,U+005F)作为分隔符有助于提高数字文字的可读性:
1_000_000_000 // A billion
101_475_938.38 // Hundreds of millions
const amount = 12345_00; // 12,345 (1234500 cents, apparently)
const amount = 123_4500; // 123.45 (4-fixed financial)
const amount = 1_234_500; // 1,234,500
0.000_001 // 1 millionth
1e10_000 // 10^10000 -- granted, far less useful / in-range...
const binary_literals = 0b1010_0001_1000_0101;
const hex_literals = 0xA0_B0_C0;
const bigInt_literals = 1_000_000_000_000n;
const octal_literal = 0o1234_5670;
结论
JavaScript 是一门充满活力的语言,这对于 Web 开发来说意义非凡。自 2015 年 ES6 发布以来,我们见证了这门语言的蓬勃发展。在本文中,我们回顾了 ES2021 中新增的一些特性。
尽管其中的许多功能对于 Web 应用程序的开发可能并非必不可少,但它们提供了以前需要使用技巧或大量冗长内容才能实现的可能性。
鏂囩珷鏉ユ簮锛�https://dev.to/carlillo/es2021-features-with-simple-examples-27d3