清除无用:ES2022中的WeakRef和FinalizationRegistry,让你的内存使用更加高效!

lxf2023-04-14 19:03:01

ES2022是ECMAScript 2022标准的简称,也称为ES12。下面是ES2022中引入的一些API及其详细说明:

1. String.prototype.replaceAll()

replaceAll()方法接受两个参数:要替换的子字符串和替换字符串。该方法会将所有的子字符串替换为新字符串,返回替换后的新字符串。

const str = "hello world!";
const newStr = str.replaceAll("o", "a");
console.log(newStr); // "hella warld!"

2. Promise.any()

Promise.any()方法接受一个Promise数组作为参数,只要其中一个Promise对象变成resolved状态,该方法就会返回该Promise对象的值。如果所有Promise对象都变成rejected状态,则抛出一个AggregateError异常。

const promises = [
  Promise.reject("error1"),
  Promise.resolve("success1"),
  Promise.reject("error2"),
  Promise.resolve("success2")
];

Promise.any(promises).then((result) => {
  console.log(result); // "success1"
}).catch((error) => {
  console.log(error); // 如果所有Promise都rejected,会抛出一个AggregateError异常
});

3. WeakRefs

WeakRefs是一种新的JavaScript对象引用类型,它允许在不阻止垃圾回收器回收对象的情况下,仍然可以跟踪这些对象的引用。这对于需要跟踪一些大型对象(如DOM元素)的引用非常有用。

let obj = { name: "John" };
const ref = new WeakRef(obj);
obj = null;

// 在这里,我们可以检查obj是否被垃圾回收了
if (ref.deref() === undefined) {
  console.log("obj has been garbage collected");
}

4. Logical Assignment Operators

ES2022引入了三个逻辑赋值运算符:||=, &&=, ??=。这些运算符可以在赋值时进行逻辑运算。

let x = 10;
x ||= 20; // 如果x为falsy,则将x赋值为20
console.log(x); // 10

let y = null;
y ??= "hello"; // 如果y为null或undefined,则将y赋值为"hello"
console.log(y); // "hello"

5. Math methods

ES2022引入了四个Math方法:Math.scale(), Math.clamp(), Math.fscale(), Math.rads()

  • Math.scale(x, inLow, inHigh, outLow, outHigh):将x从一个范围映射到另一个范围,并返回结果。
  • Math.clamp(x, min, max):将x限制在min和max之间,并返回结果。
  • Math.fscale(x, inLow, inHigh, outLow, outHigh):将x从一个范围映射到另一个范围,但与Math.scale()不同的是,该方法使用了浮点数运算。
  • Math.rads(degrees):将角度转换为弧度。
// Math.scale()
console.log(Math.scale(50, 0, 100, 0, 1)); // 0.5

// Math.clamp()
console.log(Math.clamp(10, 0, 5)); // 5
console.log(Math.clamp(2, 0, 5)); // 2

// Math.fscale()
console.log(Math.fscale(50, 0, 100, 0, 1)); // 0.5

// Math.rads()
console.log(Math.rads(180)); // 3.141592653589793

总结

ECMAScript 2022(ES2022)是JavaScript语言的最新版本,包含了一些新的特性和改进,其中一些特性已经被广泛支持。其中一些新特性包括:

  • String.prototype.replaceAll()方法,可以替换字符串中的所有匹配项。
  • Promise回调函数中的return语句,可以简化异步函数的写法。
  • 数字和数学API的扩展,包括Math.scale()Math.clamp()Math.fscale()Math.rads()等。
  • 类型转换的改进,包括字符串到数字的隐式转换,和bigint类型的增强支持。
  • WeakRef对象和FinalizationRegistry对象,可用于跟踪和释放内存中的无用对象。