没想到啊,ES2021居然更新了这样的5个 API

陈大鱼头 ... 2021-8-3 Js
  • 前端
  • Js
  • Api
  • 面试
About 3 min

如果没什么特殊情况,每一年 tc39 (opens new window) 都会更新一些特性 API ,今年出的则是第 12 版,也就是我们说的 ES12 ,下面让我们一起来看看都更新了哪些 API。

# 数字分隔符(Numeric Separators)

众所周知,我们的 Number 是长这样的:123456 。但是当金额大了之后,就会很不直观,每次看还得算,不过如今我们可以这样:

// 旧的方案
const count1 = 123456789;

// 新的方案
const count2 = 123_456_789;

console.log(count2); // 123456789
1
2
3
4
5
6
7

# String.prototype.replaceAll()

新的 replaceAll() 可以直接替换全部匹配的字符,就像这样:

'好一朵美丽的茉莉花,茉莉花啊,茉莉花啊,你又香又好看'.replaceAll('茉莉花', '玫瑰花');
// 好一朵美丽的玫瑰花,玫瑰花啊,玫瑰花啊,你又香又好看
1
2

但是如果你在 replaceAll() 里用 g 以外的标识符,或者不加 g ,都会报错,例如:

'好一朵美丽的茉莉花,茉莉花啊,茉莉花啊,你又香又好看'.replaceAll(/茉莉花/, '玫瑰花');
// Uncaught TypeError: String.prototype.replaceAll called with a non-global RegExp argument
1
2

所以这个只是 g 的语法糖。。。

# 逻辑赋值运算符(Logical Assignment Operators)

这次也更新了一些运算符,以后写起短链表达式来就方便多了。

# And and equals 运算符 (&&=)

&&= 仅在左操作数为 truthy 时才执行赋值。

let a = 1;
let b = 2;
a &&= b;
console.log(a); // 2

// 等价于
if (a) {
    a = b;
}
console.log(a); // 2
1
2
3
4
5
6
7
8
9
10

# Or or equals (||=)

||=&&= 相反,仅当左操作数为 falsy 时才执行赋值。

let a = undefined;
let b = 2;

a ||= b;
console.log(a); // 2

// 等价于
if (!a) {
    a = b;
}
1
2
3
4
5
6
7
8
9
10

# Question question equals (??=)

??= 仅当左操作数为 null 或者 undefined 才执行赋值。

let a = undefined;
let b = 2;

a ??= b;
console.log(a); // 2

// 等价于
if (a === null || a === undefined) {
    a = b;
};
1
2
3
4
5
6
7
8
9
10

# Promise.any

这次 Promise 出了一个新方法 Promise.any ,跟 Promise.all 正好相反,只要有一个是 promisefulfilled 时,则直接返回该结果,如果都是 rejected ,则报错 。

Promise
  .any([
    Promise.reject('rejected'),
    Promise.resolve('fulfilled')
	])
	.then(res => console.log(res))
	.catch(err => console.error(err));
// fulfilled

Promise
  .any([
    Promise.reject('rejected1'),
    Promise.reject('rejected2')
	])
	.then(res => console.log(res))
	.catch(err => console.error(err));
// AggregateError: All promises were rejected

Promise
  .any([
    Promise.resolve('resolve1'),
    Promise.resolve('resolve1')
	])
	.then(res => console.log(res))
	.catch(err => console.error(err));
// resolve1
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

# WeakRefs

WeakRefWeak References(弱引用) 的简写,其主要用途是对另一个对象进行弱引用。这就意味着它不会阻止GC(garbage collector 垃圾收集器)收集对象。当我们不想将对象永远保存在内存中时,这就很有用了。但是使用的时候要慎重,因为有可能出现要使用时,被引用对象已经被回收的情况。就连 TC39 提案都建议能不用就不用。

const newRef = new WeakRef({
     name: '鱼头',
     age: '26',
     sex: '男'
});

const obj = newRef.deref();

console.log(obj); // {name: "鱼头", age: "26", sex: "男"}
1
2
3
4
5
6
7
8
9

# 参考资料

  1. What's new in ECMAScript 2021 (opens new window)
  2. Ecma TC39 (opens new window)
  3. [ECMAScript] TC39 process (opens new window)
  4. The TC39 Process (opens new window)

# 后记

如果你喜欢探讨技术,或者对本文有任何的意见或建议,非常欢迎加鱼头微信好友一起探讨,当然,鱼头也非常希望能跟你一起聊生活,聊爱好,谈天说地。 鱼头的微信号是:krisChans95 也可以扫码关注公众号,订阅更多精彩内容。 https://bucket.krissarea.com/blog/base/qrcode-all1.png

Last update: June 25, 2023 00:16
Contributors: fish_head , 陈大鱼头