Skip to content

ES2020 新标准

01 bigInt

大数字,这个不受到最大和最小数字的显示,直接在数字末尾加一个N,可以确保精度;界面打印还会包括这个 n

let num = 1234567899876543212345678n;
num++;

长数值可以使用数值分隔符,例如下面两种方式结果一致,a 使用下划线分隔符,便于阅读(便于数几个0)。

a = 100_000_000_000
b = 100000000000

b = 1256_8000
b = 12568000

02 动态异步导入

导入 + await ,可以选择性导入模块,这个 webpack 也能处理对应的语法

if (num > 100) {
  let module = await import('../utils');
  module.runNode(num);
}

03 空值运算

传统的 || 处理空值,包括了 false NaN 也表示空

新加的 ?? 处理控制,把 false NaN 都视为正常值,只处理 null undefiend

false || num 
NaN || num

false ?? num
NaN ?? num

不变的

null ?? num
undefined ?? num

04 可选链

不需要判断对象的属性是否存在,即可调用对象的属性和方法,不会报错。

当时需要保证第一个对象是存在的 即 column 是存在的

column?.data?.option?.map()

05 Promise

Promise.race:Promse 赛跑,意思就是说,Promise.race([p1, p2, p3])里面哪个结果获得的快,就返回那个结果,不管结果本身是成功状态还是失败状态。

Promise.any:只要这个方法返回了 Promise 列表 / 数组中的第一个已解析的 Promise,就会短路并返回一个值。如果所有的 promise 都被拒绝,那么它将抛出一个汇总错误消息。它与 Promise.race() 不同,因为一旦给定的 Promise 之一被解析或拒绝,Promise.any() 方法就会短路。

Promise.allSettled

Promise.allSettled(promiseArray).then(ressults => {
  console.log("全部的结果是", results);
});

06 matchAll

返回一个匹配的组(伪数组?)

const iterator = 'adfsv'.matchAll(/[a-c]/g);
const results = Array.from(iterator);

07 golbalThis

全局 this,用于 node 和 浏览器中

08 for in 顺序

早期不同浏览器中,遍历对象的属性,for in 结果的顺序不一致,可能造成问题

新标准下已经实现了一致的顺序

09 replaceAll

下面这两种方式等价

'I love coffee coffee'.replaceAll('coffee', 'milk');

'I love coffee coffee'.replace(/coffee/g, 'milk');

特定格式

10 Intl 对象

Intl.ListFormat 列表格式

对象带有两个参数,它们都是可选的。第一个参数是语言(语言环境),第二个参数是具有两个属性(样式和类型)的选项对象。

这个用于不同语言环境下输出列表

new Intl.ListFormat([locales[, options]])

const arr = ['Pen', 'Pencil', 'Paper']

let obj = new Intl.ListFormat('en', { style: 'short', type: 'conjunction' })
console.log(obj.format(arr)) // Pen, Pencil, & Paper

obj = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' })
console.log(obj.format(arr)) // Pen, Pencil, and Paper

Intl.DateTimeFormat 时间格式

// Time only with long format
o = new Intl.DateTimeFormat('en' , { timeStyle: 'long' })
console.log(o.format(Date.now())) // 11:27:57 PM GMT+11

// Date only with short format
o = new Intl.DateTimeFormat('en' , { dateStyle: 'short'})
console.log(o.format(Date.now())) // 10/6/20

// Date only with medium format
o = new Intl.DateTimeFormat('en' , { dateStyle: 'medium'})
console.log(o.format(Date.now())) // Oct 6, 2020

// Date only with long format
o = new Intl.DateTimeFormat('en' , { dateStyle: 'long'})
console.log(o.format(Date.now())) // October 6, 2020

Last update: October 23, 2022