matchAll

  1. matchAll() 方法返回一个包含所有匹配正则表达式的结果的迭代器。可以使用 for...of 遍历,或者使用 展开运算符(...) 或者 Array.from 转换为数组.
  2. const regexp = /t(e)(st(\d?))/g;
  3. const str = 'test1test2';
  4. const matchs = str.matchAll(regexp);
  5. console.log(matchs); // RegExpStringIterator {}
  6. console.log([...matchs])
  7. /*
  8. 0: (4) ["test1", "e", "st1", "1", index: 0, input: "test1test2", groups: undefined]
  9. 1: (4) ["test2", "e", "st2", "2", index: 5, input: "test1test2", groups: undefined]
  10. length: 2
  11. /*
  12. RegExp.exec() 和 matchAll() 区别:
  13. 在 matchAll 出现之前,通过在循环中调用 regexp.exec() 来获取所有匹配项信息。
  14. const regexp = RegExp('foo[a-z]*','g');
  15. const str = 'table football, foosball';
  16. let match;
  17. while ((match = regexp.exec(str)) !== null) {
  18. console.log(`Found ${match[0]} start=${match.index} end=${regexp.lastIndex}.`);
  19. }
  20. // expected output: "Found football start=6 end=14."
  21. // expected output: "Found foosball start=16 end=24."
  22. 如果使用 matchAll ,就可以不必使用 while 循环加 exec 方式
  23. const regexp = RegExp('foo[a-z]*','g');
  24. const str = 'table football, foosball';
  25. const matches = str.matchAll(regexp);
  26. for (const match of matches) {
  27. console.log(`Found ${match[0]} start=${match.index} end=${match.index + match[0].length}.`);
  28. }
  29. // expected output: "Found football start=6 end=14."
  30. // expected output: "Found foosball start=16 end=24."

import()

  1. import 标准的用法是导入的模块是静态的,会使所有被带入的模块在加载时就被编译,无法做到按需加载编译,降低了首页的加载速度。在某些场景中,你可能希望根据条件导入模块,或者按需导入模块,这是就可以使用动态导入代替静态导入了
  2. import() 之前,我们需要更具条件导入模块时只能使用 require()
  3. if (xx) {
  4. const module = require('/module')
  5. }
  6. // 现在可以这么写
  7. if (xx) {
  8. const module = import('/module')
  9. }
  10. @babel/preset-env 已经包含了 @babel/plugin-syntax-dynamic-import,因此如果要使用 import() 语法,只需要配置 @babel/preset-env 即可。
  11. 另外:import() 返回的是一个Promise 对象:
  12. // module.js
  13. export default {
  14. name: 'shenjp'
  15. }
  16. // index.js
  17. if (true) {
  18. let module = import('./module.js');
  19. console.log(module); // Promise {<pending>
  20. module.then(data => console.log(data)); // Module {default: {name: "shenjp"}, __esModule: true, Symbol(Symbol.toStringTag): "Module"}
  21. }

import.meta

  1. import.meta对象是由ECMAScript实现的,它带有一个null的原型对象。这个对象可以扩展,并且它的属性都是可写,可配置和可枚举的。
  2. <script type="module" src="my-module.mjs"></script>
  3. console.log(import.meta); // { url: "file:///home/user/my-module.mjs" }
  4. 因为 import.meta 必须要在模块内部使用,如果不加 type="module",控制台会报错:Cannot use 'import.meta' outside a module
  5. 在项目中需要下载 @open-wc/webpack-import-meta-loader 才能正常使用。
  6. module: {
  7. rules: [
  8. {
  9. test: /\.js$/,
  10. use: [
  11. require.resolve('@open-wc/webpack-import-meta-loader'),
  12. {
  13. loader: 'babel-loader',
  14. options: {
  15. presets: [
  16. "@babel/preset-env",
  17. "@babel/preset-react"
  18. ]
  19. },
  20. }
  21. ]
  22. }
  23. ]
  24. }
  25. 效果如下:
  26. //src/index.js
  27. import React from 'react';
  28. console.log(import.meta);//{index.js:38 {url: "http://127.0.0.1:3000/src/index.js"}}

export * as ns from ‘module’

  1. ES2020新增了 export * as XX from 'module',和 import * as XX from 'module'
  2. // module.js
  3. export * as ns from './info.js'
  4. 可以理解为下面两条语句的合并:
  5. import * as ns from './info.js';
  6. export { ns };
  7. 需要注意的是:export * as ns from 'module' 并不会真的导入模块,因此在该模块中无法使用 ns

Promise.allSettled

  1. Promise.allSettled()方法返回一个在所有给定的promise都已经fulfilledrejected后的promise,并带有一个对象数组,每个对象表示对应的promise结果。
  2. 当您有多个彼此不依赖的异步任务成功完成时,或者您总是想知道每个promise的结果时,通常使用它。
  3. 想比较之下, Promise.all() 更适合做相互依赖的Promise,只要有一个失败就结束
  4. 复制代码
  5. const promise1 = Promise.resolve(100);
  6. const promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, 'info'));
  7. const promise3 = new Promise((resolve, reject) => setTimeout(resolve, 200, 'name'))
  8. Promise.allSettled([promise1, promise2, promise3]).
  9. then((results) => console.log(result));
  10. /*
  11. [
  12. { status: 'fulfilled', value: 100 },
  13. { status: 'rejected', reason: 'info' },
  14. { status: 'fulfilled', value: 'name' }
  15. ]
  16. */
  17. 复制代码
  18. 可以看出,Promise.allSettled() 成功之后返回的也是一个数组,但是改数组的每一项都是一个对象,每个对象都有一个status属性,值为 fulfilled rejected .
  19. 如果status fulfilled,那么改对象的另一个属性是 value ,对应的是该Promise成功后的结果。
  20. 如果status rejected,那么对象的另一个属性是 reason,对应的是该Promise失败的原因。

BigInt

  1. BigInt 是一种数字类型的数据,它可以表示任意精度格式的整数。在此之前,JS 中安全的最大数字是 9009199254740991,即2^53-1,在控制台中输入 Number.MAX_SAFE_INTEGER 即可查看。超过这个值,JS 没有办法精确表示。另外,大于或等于21024次方的数值,JS 无法表示,会返回 Infinity
  2. BigInt 即解决了这两个问题。BigInt 只用来表示整数,没有位数的限制,任何位数的整数都可以精确表示。为了和 Number 类型进行区分,BigInt 类型的数据必须添加后缀 n.
  3. 复制代码
  4. //Number类型在超过9009199254740991后,计算结果即出现问题
  5. const num1 = 90091992547409910;
  6. console.log(num1 + 1); //90091992547409900
  7. //BigInt 计算结果正确
  8. const num2 = 90091992547409910n;
  9. console.log(num2 + 1n); //90091992547409911n
  10. 复制代码
  11. 我们还可以使用 BigInt 对象来初始化 BigInt 实例:
  12. console.log(BigInt(999)); // 999n 注意:没有 new 关键字!!!
  13. 需要说明的是,BigInt Number 是两种数据类型,不能直接进行四则运算,不过可以进行比较操作。
  14. console.log(99n == 99); //true
  15. console.log(99n === 99); //false
  16. console.log(99n + 1);//TypeError: Cannot mix BigInt and other types, use explicit conversionss

GlobalThis

  1. JS 中存在一个顶层对象,但是,顶层对象在各种实现里是不统一的。
  2. 从不同的 JavaScript 环境中获取全局对象需要不同的语句。在 Web 中,可以通过 windowself 取到全局对象,但是在 Web Workers 中,只有 self 可以。在 Node.js 中,它们都无法获取,必须使用 global
  3. var getGlobal = function () {
  4. if (typeof self !== 'undefined') { return self; }
  5. if (typeof window !== 'undefined') { return window; }
  6. if (typeof global !== 'undefined') { return global; }
  7. throw new Error('unable to locate global object');
  8. };
  9. ES2020 中引入 globalThis 作为顶层对象,在任何环境下,都可以简单的通过 globalThis 拿到顶层对象。

空值合并运算符

  1. ES2020 新增了一个运算符 ??。当左侧的操作数为 null 或者 undefined时,返回其右侧操作数,否则返回左侧操作数。
  2. 在之前我们经常会使用 || 操作符,但是使用 || 操作符,当左侧的操作数为 0 null undefined NaN false '' 时,都会使用右侧的操作数。如果使用 || 来为某些变量设置默认值,可能会遇到意料之外的行为。
  3. ?? 操作符可以规避以上问题,它只有在左操作数是 null 或者是 undefined 时,才会返回右侧操作数。
  4. const someValue = 0;
  5. const defaultValue = 100;
  6. let value = someValue ?? defaultValue; // someValue 为 0 ,value 的值是 0

可选链操作符

  1. 可选链操作符 ?. 允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。?. 操作符的功能类似于 . 链式操作符,不同之处在于,在引用为空(nullish, null 或者 undefined) 的情况下不会引起错误,该表达式短路返回值是 undefined
  2. 例如,我们要访问 info 对象的 animal reptile tortoise。但是我们不确定 animal, reptile 是否存在,因此我们需要这样写:
  3. const tortoise = info.animal && info.animal.reptile && info.animal.reptile.tortoise;
  4. 因为 null.reptile undefined.reptile 会抛出错误:TypeError: Cannot read property 'reptile' of undefined TypeError: Cannot read property 'reptile' of null,为了避免报错,如果我们需要访问的属性更深,那么这个这句代码会越来越长。
  5. 有了可选链之后我们就可以简化:
  6. const tortoise = info.animal?.reptile?.tortoise;
  7. 可以看到可选链操作符 ?. 和空位合并操作符一样,都是针对的 null undefined 这两个值。