es新特性

(一) ES2021
1.String.prototype.replaceAll()
'koofe'.replace('o', 'ô');
等同于 'koofe'.replace(/o/g, 'ô');
2.Promise.all:
只要有一个 promise 是 rejected,则立即返回一个 rejected promise;所有的 promise 都是 fulfilled 时,则返回一个 resolved promise
3.逻辑赋值运算符

 a ||= b;

 // 与 a ||= b 等价
 a || (a = b);

 // 与 a ||= b 等价
 if (!a) {
   a = b;
 } 

 a &&= b;

 // 与 a &&= b 等价
 a && (a = b);

 // 与 a &&= b 等价
 if (a) {
   a = b;
 } 
 a ??= b;

// 与 a ??= b 等价
 a ?? (a = b);

 // 与 a ??= b 等价
 if (a === null || a === undefined) {
   a = b;
 } 
let obj = {};

obj.x ??= 0;
console.log(obj.x) // 0

obj.x ||= 1;
console.log(obj.x) // 1

obj.x &&= 2;
console.log(obj.x) // 2

a = a || b; // 与 a ||= b 不等价
a = a && b; // 与 a &&= b 不等价
a = a ?? b; // 与 a ??= b 不等价

4.数字分隔符
使用 _ 对数字进行分割,提高数字的可读性,例如在日常生活中数字通常是每三位数字之间会用 , 分割,以方便人快速识别数字

// 1000000000 不易辨识
const count1 = 1000000000;

// 1_000_000_000 很直观
const count2 = 1_000_000_000;

console.log(count1 === count2); // true

5.WeakRefs
WeakRef 实例可以作为对象的弱引用,对象的弱引用是指当该对象应该被 GC 回收时不会阻止 GC 的回收行为。而与此相反的,一个普通的引用(默认是强引用)会将与之对应的对象保存在内存中。只有当该对象没有任何的强引用时,JavaScript 引擎 GC 才会销毁该对象并且回收该对象所占的内存空间。因此,访问弱引用指向的对象时,很有可能会出现该对象已经被回收,WeakRef 使用方法如下:

const ref = new WeakRef({ name: 'koofe' });
let obj = ref.deref();
if (obj) {
  console.log(obj.name); // koofe
}

(一) ES2020
1.String.prototype.matchAll
String.prototypematch() 方法仅返回完整的匹配结果,却不会返回特定正则表达式组(Regex groups)的信息。它返回了远比 match() 多得多的信息——它返回的迭代器不仅包括精确的匹配结果,还有全部的正则模式捕获结果。你还记得由 Gorkem Yakin 和 Daniel Ehrenberg 在 ECMAScript 2018 中新增的[命名捕获组吗? matchAll() 方法完美实现了它

// :matchAll() 方法,可以看到结果的 groups 为命名捕获组
const text = "From 2019.01.29 to 2019.01.30";
const regexp = /(?\d{4}).(?\d{2}).(?\d{2})/gu;
const results = Array.from(text.matchAll(regexp));
console.log(results);
// [
//   [
//     '2019.01.29',
//     '2019',
//     '01',
//     '29',
//     index: 5,
//     input: 'From 2019.01.29 to 2019.01.30',
//     groups: [Object: null prototype] { year: '2019', month: '01', day: '29' }
//   ],
//   [
//     '2019.01.30',
//     '2019',
//     '01',
//     '30',
//     index: 19,
//     input: 'From 2019.01.29 to 2019.01.30',
//     groups: [Object: null prototype] { year: '2019', month: '01', day: '30' }
//   ]
// ]

2.import()
ECMAScript 2015 引入了静态模块,与之相对应的是, 由[Domenic Denicola) 提出的可以按需获取的动态 import. 该类函数格式(它并非继承自 Function.prototype)返回了一个强大的 promise 函数,使得诸如按需引入、可计算模块名以及脚本内计算均成为可能。

const modulePage = 'page.js'; 

import(modulePage)
     .then((module) => {
        module.default();
     });
(async () => {
  const helpersModule = 'helpers.js';
  const module = await import(helpersModule)
  const total = module.sum(2, 2);
})();

3.BigInt – 任意精度整数
Number.MAX_SAFE_INTEGER 不再是 JavaScript 的限制。BigInt 是一个新的原语,它可以表示任意精度的整数。你可以通过 BigInt 方法,或是在一个数值后添加 n 后缀,来将一个 number 转换为 bigint 类型。

Number.MAX_SAFE_INTEGER
// 9007199254740991
Number.MAX_SAFE_INTEGER + 10 -10
// 9007199254740990   (译者注:精度丢失)
BigInt(Number.MAX_SAFE_INTEGER) + 10n -10n
// 9007199254740991n  (译者注:计算结果为 bigint 类型)

4.Promise.allSettled
它可以用在处理所有的 promise 都 settled 的情况,无论结果是 fulfilled 还是 rejected. 你看 ,无需 catch

Promise.allSettled([
  fetch("https://api.github.com/users/pawelgrzybek").then(data => data.json()),
  fetch("https://api.github.com/users/danjordan").then(data => data.json())
])
  .then(result => console.log(`All profile settled`));

5.globalThis
所以在 JavaScript 中,全局的 this 到底是什么?在浏览器中它是 window, 在 worker 中它是 self, 在 Node.js 中它是 global, 在.. 如今这种混乱终于结束了

6.for-in 机制
7.可选链

// 之前
const title = data && data.article && data.article.title
// 之后
const title = data?.article?.title

8.空值合并运算符

特性紧随「可选链」之后。与 || 相比,空值合并运算符 ?? 只会在左边的值严格等于 null 或 undefined 时起作用。

9.import.meta
[Domenic Denicola]提出的 [import.meta 提议])为当前运行的模块添加了一个特定 host 元数据对象。

console.log(import.meta.url)

10.export * as ns from “mod”

export * as ns from "mod"

(一) ES2019
1.Array.prototype flat, flatMap
数组打平
另一个和它一起提供的是flatMap方法,其实就相当于flat和map一起组合操作
2.Object.fromEntries

var obj = {a: 1, b: 2, c: 3, d: 4};
var entries = Object.entries(obj);
var newObj = Object.fromEntries(entries);
console.log(newObj); // {a: 1, b: 2, c: 3, d: 4}

3.String.protope.{trimstart, trimEnd}
官方又提供了另外两个API: trimStart和trimEnd,可以分别去除头和尾上的空格、换行
4.Symbol.protoype.description
从es6开始,javascript中引入了Symbol这个基本数据类型,可以实现一些数据内省等高级功能。在es2019中在Symbol类型上增加了description属性用来获取Symbol类型数据的描述信息

let testSymbol = Symbol('test symbol');
testSymbol.description // test symbol

5.可选catch参数
在进行try catch错误处理过程中,你如果没有给catch传参数的话,代码就会报错。在es2019中,你可以选择性地不给它传入参数。一个比较常见的使用场景是: 在使用JSON.parse解析字符串的时候,虽然你知道可能会报错,但是你并不关心这个错误,这时候你就可以把错误参数吞掉。
···
// 原先的代码可能长这样:
try {
// do something
} catch(e) {
console.log(e);
}
// 新的代码
try {
// do something
} catch {
// do other thing without error parameter
}
···
6.Function.prototype.toString
之前对于函数对象调用toString方法,会将它定义过程中的注释等信息去掉,现在会原样进行输出:

var sayHello = function() {
    // do something
    console.log('hello world')
}
sayHello.toString();
// "function() {
    // do something
    console.log('hello world')
}"

7.JSON.superset 超集
之前如果JSON字符串中包含有行分隔符 (\u2028) 和段落分隔符 (\u2029),那么在解析过程中会报错:SyntaxError: Invalid or unexpected token。es2019中新增了对它们的支持。

(一) ES2018
1.async/await 异步迭代循环
async function foo(array) {
for await (let i of array) {
doSomething(i);
}
}
2.Promise.finally()
3.Rest/Spread 属性

function foo(a, b, ...rest) {
  // a = 1
  // b = 2
  // rest = [3, 4, 5]
}
foo(1, 2, 3, 4, 5);

4.正则表达式 s(dotAll模式)标记
在正则中,.可以匹配任意字符,除了换行符。

/hello.es9/.test('hello\nes9');
// false

ES2018引入了dotAll模式,通过使用标记s选项,.就可以匹配换行符。

/hello.es9/s.test('hello\nes9');
// true

正则表达式 Unicode 转义
目前在正则中,可以通过字符集的名称来匹配字符。如s代表空白

/^\s+$/u.test(' ');
// true

在ES2018添加了Unicode属性转义,形式为\p{...}和\P{...},在正则表达式中使用标记u(unicode) 选项。

/^\p{White_Space}+$/u.test(' ') // 空格
// true
/^\p{Script=Greek}+$/u.test('μετά') // 希腊字母
// true
/^\p{Script=Latin}+$/u.test('Grüße') // 匹配拉丁字母
// true
/^\p{Surrogate}+$/u.test('\u{D83D}') // 匹配单独的替代字符
// true

lookbehind 反向断言
目前JavaScript在正则表达式中支持先行断言(lookahead)。这意味着匹配会发生,但是断言没有包含在整个匹配字段中。

如匹配字符串“10 hours”中紧跟着是”hours”的数字:

const reg = /\d+(?= hours)/u;
const matched = reg.exec('10 hours');
matched[0];
// 42
匹配字符串“10 minutes”中紧跟着不是”hours”的数字:

const reg = /\d+(?! hours)/u;
const matched = reg.exec('10 minutes');
matched[0];
// 42
ES2018引入以相同方式工作但是匹配前面的反向断言(lookbehind)。

匹配字符串“hours10”中”hours”后面的数字:

const reg = /(?<=hours)\d+/u;
const matched = reg.exec('hours10');
matched[0];

匹配字符串“minutes10”中数字前面不是“hours”:

const reg = /(?

Named capture groups 正则表达式命名捕获组
目前,正则表达式中小括号匹配的分组是通过索引编号的:

const reg = /(\d{4})-(\d{2})-(\d{2})/u;
const matched = reg.exec('2018-12-31');
matched[0];  // 2018-12-12
matched[1];  // 2018
matched[2];  // 12
matched[3];  // 31

代码可读性较差,并且改变正则表达式的结构有可能改变匹配对象的索引。

ES2018允许命名捕获组使用符号?, 可以指定小括号中匹配内容的名称放在groups里,这样可以提高代码的可读性。

const reg = /(?\d{4})-(?\d{2})-(?\d{2})/u;
const matched = reg.exec('2018-12-31');
matched.groups.year;  // 2018
matched.groups.month;  // 12
matched.groups.day;  // 31

命名捕获组也可以使用在replace()方法中。例如将日期转换为“年月日”格式:

const reg = /(?\d{4})-(?\d{2})-(?\d{2})/u;
'2018-12-31'.replace(reg, '$年$月$日');
// 2018年12月31日

非转义序列的模板字符串
ES2018 移除对 ECMAScript 在带标签的模版字符串中转义序列的语法限制。

之前,\u开始一个 unicode 转义,\x开始一个十六进制转义,\后跟一个数字开始一个八进制转义。这使得创建特定的字符串变得不可能,例如Windows文件路径 C:\uuu\xxx\111。。
(一) ES2017
1.Async 函数呈现更清晰的 Promise 语法
2.使用Object.values()遍历对象的属性值,无需使用使用属性名
3.使用Object.entries()遍历对象的属性名和属性值
4.Object.getOwnPropertyDescriptors() 方法用来获取一个对象的所有自身属性的描述符
5.padStart()方法用另一个字符串填充当前字符串(如果需要,多次),直到结果字符串达到给定长度。填充从当前字符串的开头(左侧)开始应用。
padEnd() 方法会用一个字符串填充当前字符串(如果需要的话则重复填充),返回填充后达到指定长度的字符串。从当前字符串的末尾(右侧)开始填充。
6.结尾逗号,数组定义和函数参数列表

// ES2017 is happy!
const a = [1, 2, 3,];

const b = {
  a: 1,
  b: 2,
  c: 3,
};

function c(one,two,three,) {};

7.SharedArrayBuffer and Atomics

你可能感兴趣的:(es新特性)