ES11
ECMAScript 11(简称ES11)是于2020年6月正式发布的JavaScript语言的标准,正式名为ECMAScript 2020(ES2020)。
# String.prototype.matchAll
该方法返回一个包含所有匹配正则表达式的结果及分组捕获组的迭代器。
语法:
str.matchAll(regexp)
参数:
- regexp:正则表达式对象。如果所传参数不是一个正则表达式对象,则会隐式地使用 new RegExp(obj) 将其转换为一个 RegExp 。RegExp必须是设置了全局模式g的形式,否则会抛出异常TypeError。
返回值:一个迭代器(不可重用,结果耗尽需要再次调用方法,获取一个新的迭代器)。
示例:
// 在 matchAll 出现之前,通过在循环中调用 regexp.exec() 来获取所有匹配项信息(regexp 需使用 /g 标志):
const regexp = RegExp('foo[a-z]*','g');
const str = 'table football, foosball';
let match;
while ((match = regexp.exec(str)) !== null) {
console.log(`Found ${match[0]} start=${match.index} end=${regexp.lastIndex}.`);
// Found football start=6 end=14.
// Found foosball start=16 end=24.
}
// 使用 matchAll
const matches = str.matchAll(regexp);
for (const match of matches) {
console.log(`Found ${match[0]} start=${match.index} end=${match.index + match[0].length}.`);
}
// Found football start=6 end=14.
// Found foosball start=16 end=24.
// 再次调用 matchAll 创建一个新的迭代器
Array.from(str.matchAll(regexp), m => m[0]);
// Array [ "football", "foosball" ]
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
注意
如果没有 /g 标志,matchAll 会抛出异常。
# BigInt
BigInt 是一种内置对象,它提供了一种方法来表示大于 2^53 - 1 的整数。这原本是 Javascript中可以用 Number 表示的最大数字。BigInt 可以表示任意大的整数。
// 可以用在一个整数字面量后面加 n 的方式定义一个 BigInt ,如:10n,或者调用函数 BigInt()(但不包含 new 运算符)并传递一个整数值或字符串值。
const theBiggestInt = 9007199254740991n;
const alsoHuge = BigInt(9007199254740991343434);
// ↪ 9007199254740991n
const hugeString = BigInt("9007199254740991");
// ↪ 9007199254740991n
const hugeHex = BigInt("0x1fffffffffffff");
// ↪ 9007199254740991n
const hugeBin = BigInt("0b11111111111111111111111111111111111111111111111111111");
// ↪ 9007199254740991n
2
3
4
5
6
7
8
9
10
11
12
13
14
相关信息
- 使用 typeof 测试时, BigInt 对象返回 "bigint" :
typeof 1n === 'bigint'; // true typeof BigInt('1') === 'bigint'; // true
1
2 - 使用 Object 包装后, BigInt 被认为是一个普通 "object" :
typeof Object(1n) === 'object'; // true
1
# Promise.allSettled
该方法返回一个在所有给定的promise都已经fulfilled或rejected后的promise,并带有一个对象数组,每个对象表示对应的promise结果。 当您有多个彼此不依赖的异步任务成功完成时,或者您总是想知道每个promise的结果时,通常使用它。
语法:
Promise.allSettled(iterable);
参数:
- iterable:一个可迭代的对象,例如Array,其中每个成员都是Promise。
返回值:一旦所指定的 promises 集合中每一个 promise 已经完成,无论是成功的达成或被拒绝,该数组包含原始 promises 集中每个 promise 的结果。
使用场景:等待多个 promise 返回结果时,我们可以用 Promise.all([promise_1, promise_2])。但问题是,如果其中一个请求失败了,就会抛出错误。然而,有时候我们希望某个请求失败后,其他请求的结果能够正常返回。
const promise_1 = Promise.resolve('hello')
const promise_2 = new Promise((resolve, reject) => setTimeout(reject, 200, 'problem'))
Promise.allSettled([promise_1, promise_2])
.then(([promise_1_result, promise_2_result]) => {
console.log(promise_1_result) // 输出:{status: 'fulfilled', value: 'hello'}
console.log(promise_2_result) // 输出:{status: 'rejected', reason: 'problem'}
})
2
3
4
5
6
7
8
# globalThis
在以前,从不同的 JavaScript 环境中获取全局对象需要不同的语句。在 Web 中,可以通过 window、self 或者 frames 取到全局对象,但是在 Web Workers 中,只有 self 可以。在 Node.js 中,它们都无法获取,必须使用 global。
在非严格模式下,可以在函数中返回 this 来获取全局对象,但是在严格模式和模块环境下,this 会返回 undefined。你也可以使用 Function('return this')(),但那些禁用eval()的环境,如在浏览器中的CSP,不允许这样使用Function。
globalThis 提供了一个标准的方式来获取不同环境下的全局 this 对象(也就是全局对象自身)。不像 window 或者 self 这些属性,它确保可以在有无窗口的各种环境下正常工作。所以,你可以安心的使用 globalThis,不必担心它的运行环境。为便于记忆,你只需要记住,全局作用域中的 this 就是 globalThis。
// 浏览器
window == globalThis // true
// node.js
global == globalThis // true
// 在 globalThis 之前,获取某个全局对象的唯一方式就是 Function('return this')();
var getGlobal = function () {
if (typeof self !== 'undefined') { return self; }
if (typeof window !== 'undefined') { return window; }
if (typeof global !== 'undefined') { return global; }
throw new Error('unable to locate global object');
};
var globals = getGlobal();
if (typeof globals.setTimeout !== 'function') {
// 此环境中没有 setTimeout 方法!
}
// 但是有了 globalThis 之后,只需要:
if (typeof globalThis.setTimeout !== 'function') {
// 此环境中没有 setTimeout 方法!
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# Optional Chaining(可选链式调用?.)
一种可以在当前值可能为null的可选值上请求和调用属性、方法及下标的方法。
const obj = {
name: '小明',
}
const arr = [1, 2, 3]
let fn = () => {
console.log('fn')
}
//1、访问对象属性
console.log(obj.name) // 小明
console.log(obj.name?.age) // undefined
//2、访问数组
console.log(arr[1]) // 2
console.log(arr[3]?.toFixed()) // undefined
//3、调用函数
console.log(fn()); // fn
fn = null;
console.log(fn?.()); // undefined
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Nullish Coalescing(空值合并操作符??)
是一个逻辑操作符,当左侧的操作数为 null 或者 undefined 时,返回其右侧操作数,否则返回左侧操作数。
console.log(null ?? 'default'); // default
console.log(undefined ?? 'default'); // default
console.log(false ?? 'default'); // false
console.log(true ?? 'default'); // true
console.log(0 ?? 'default'); // 0
console.log(-0 ?? 'default'); // -0
console.log('' ?? 'default'); // ''
2
3
4
5
6
7
# import.meta
import.meta是一个给JavaScript模块暴露特定上下文的元数据属性的对象。它包含了这个模块的信息,比如说这个模块的URL。
<script type="module" src="my-module.mjs"></script>
console.log(import.meta); // { url: "file:///home/user/my-module.mjs" }
2
# for-in mechanics
以前在不同的引擎下for in循环出来的内容顺序是可能不一样的,现在标准化了。
# import()
有时候我们需要动态加载一些模块,这时候就可以使用 import() 了。标准用法的import导入的模块是静态的,会使所有被导入的模块,在加载时就被编译(无法做到按需编译,降低首页加载速度)。有些场景中,你可能希望根据条件导入模块或者按需导入模块,这时你可以使用动态导入代替静态导入。下面的是你可能会需要动态导入的场景:
- 当静态导入的模块很明显的降低了代码的加载速度且被使用的可能性很低,或者并不需要马上使用它。
- 当静态导入的模块很明显的占用了大量系统内存且被使用的可能性很低。
- 当被导入的模块,在加载时并不存在,需要异步获取
- 当导入模块的说明符,需要动态构建。(静态导入只能使用静态说明符)
- 当被导入的模块有副作用(这里说的副作用,可以理解为模块中会直接运行的代码),这些副作用只有在触发了某些条件才被需要时。(原则上来说,模块不能有副作用,但是很多时候,你无法控制你所依赖的模块的内容)
注意
请不要滥用动态导入(只有在必要情况下采用)。静态框架能更好的初始化依赖,而且更有利于静态分析工具和tree shaking发挥作用
// import可以像调用函数一样来动态的导入模块。以这种方式调用,将返回一个 promise。
import('/modules/my-module.js')
.then((module) => {
// Do something with the module.
});
// 也支持 await 关键字。
let module = await import('/modules/my-module.js');
2
3
4
5
6
7
8