ES12

2022/4/23 20:10 Javascript 大约 3 分钟

ECMAScript 12(简称ES12)是于2021年6月正式发布的JavaScript语言的标准,正式名为ECMAScript 2021(ES2021)。

# String.protoype.replaceAll

该方法返回一个新字符串,新字符串所有满足 pattern 的部分都已被replacement 替换。pattern可以是一个字符串或一个 RegExp, replacement可以是一个字符串或一个在每次匹配被调用的函数。

语法:

const newStr = str.replaceAll(regexp|substr, newSubstr|function)
1

相关信息

  1. 此方法不会更改调用 String 对象。它只是返回一个新字符串。
  2. 当使用一个 regex时,您必须设置全局(“ g”)标志,否则,它将引发 TypeError:“必须使用全局 RegExp 调用 replaceAll”。
'aabbcc'.replaceAll('b', '.');
// aa..cc

'aabbcc'.replaceAll(/b/g, '.');
// aa..cc

// 之前
const str = '2-4-6-8-10';
const newStr = str.replace(/\-/g, '+');
console.log(newStr); //2+4+6+8+10

// 现在可以
const str2 = '2-4-6-8-10';
const newStr2 = str2.replaceAll('-', '+');
console.log(newStr2); //2+4+6+8+10

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# Promise.any

Promise.any() 接收一个Promise可迭代对象,只要其中的一个 promise 成功,就返回那个已经成功的 promise 。如果可迭代对象中没有一个 promise 成功(即所有的 promises 都失败/拒绝),就返回一个失败的 promise 和AggregateError类型的实例,它是 Error 的一个子类,用于把单一的错误集合在一起。本质上,这个方法和Promise.all()是相反的。

const pErr = new Promise((resolve, reject) => {
  reject("总是失败");
});

const pSlow = new Promise((resolve, reject) => {
  setTimeout(resolve, 500, "最终完成");
});

const pFast = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, "很快完成");
});

Promise.any([pErr, pSlow, pFast]).then((value) => {
  console.log(value);
  // pFast fulfils first
})
// 期望输出: "很快完成"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

相关信息

即使第一个返回的 promise 是失败的,Promise.any() 依然使用第一个成功状态的 promise 来返回。

# WeakRefs

WeakRef对象允许您保留对另一个对象的弱引用,而不会阻止被弱引用对象被GC回收.

WeakRef对象包含对对象的弱引用,这个弱引用被称为该WeakRef对象的target或者是referent。对对象的弱引用是指当该对象应该被GC回收时不会阻止GC的回收行为。而与此相反的,一个普通的引用(默认是强引用)会将与之对应的对象保存在内存中。只有当该对象没有任何的强引用时,JavaScript引擎GC才会销毁该对象并且回收该对象所占的内存空间。如果上述情况发生了,那么你就无法通过任何的弱引用来获取该对象。

注意

对于WeakRef对象的使用要慎重考虑,能不使用就尽量不要使用

let ref = new WeakRef({})
let isLive = ref.deref() // 如果 obj 被垃圾回收了,那么 isLive 就是 undefined

// 在一个DOM元素中启动一个计数器,当这个元素不存在时停止:
class Counter {
    constructor(element) {
        // Remember a weak reference to the DOM element
        this.ref = new WeakRef(element);
        this.start();
    }

    start() {
        if (this.timer) {
            return;
        }

        this.count = 0;

        const tick = () => {
            // 从弱引用中获取元素,如果它仍然存在
            const element = this.ref.deref();
            if (element) {
                element.textContent = ++this.count;
            } else {
                console.log("元素不存在");
                this.stop();
                this.ref = null;
            }
        };

        tick();
        this.timer = setInterval(tick, 1000);
    }

    stop() {
        if (this.timer) {
            clearInterval(this.timer);
            this.timer = 0;
        }
    }
}

const counter = new Counter(document.getElementById("counter"));
counter.start();
setTimeout(() => {
    document.getElementById("counter").remove();
}, 5000);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

# Logical Assignment Operators(逻辑赋值操作符)

a ||= b; // 等同于 a || (a = b);

a &&= b; // 等同于 a && (a = b);

a ??= b; // 等同于 a ?? (a = b);
1
2
3
4
5

# Numeric separators (数字分隔符)

可以在数字之间创建可视化分隔符,通过_下划线来分割数字,使数字化可计算。

const money = 1_000_000_000;
//等价于
const money2 = 1000000000;

console.log(1_000_000_000 === 1000000000); // true

let budget = 1_000_000_000_000;
console.log(budget === 10 ** 12); // true
1
2
3
4
5
6
7
8
上次编辑于: 2023年7月4日 09:36