ECMA 2020 新特性
Apr 05, 2021 • 🍻 02min 09s read
🔖 javascriptecmascript
?.
操作符
?.
是链式调用操作符,当操作符左侧变量不存在时会返回 undefined
,并中断链式调用。其英文名称为 Optional chaining for property accesses and method calls
Demo
123o?.propo?.['prop']f?.(arg1, arg2)等价于
123(o !== undefined && o !== null) ? o.prop : undefined(o !== undefined && o !== null) ? o['prop'] : undefined(f !== undefined && f !== null) ? f(arg1, arg2) : undefined需要注意,当操作符左侧不是可调用的对象时,如
true?.(123)
则会产生一个TypeError
异常;因为此操作符的设计目的是容忍刻意的省略,因此对于类型错误应该抛出异常,而不是忽略它。对于带有
?.
的链式调用,当中间路径不存在时,中间的函数调用不会得到执行,如:12345678function isInvoked(obj) {let invoked = false;obj?.a.b.m(invoked = true);return invoked;}isInvoked({a: {b: {m() {}}}}) // => trueisInvoked(undefined) {}}}}) // => false
??
操作符
??
操作符类似 ||
,只不过其中断条件为非 null
或 undefined
值,而 ||
中断条件为任意 Truthy 的值。其英文名称为 Nullish coalescing operator
示例
1a ?? b等价于
1(a !== undefined && a !== null) ? a : b短路赋值用法(ES2021):
a ??= b
等价于a ?? (a = b)
BigInt
以
n
结尾的数字会自动转成BigInt
12n**53n + 1n // => 9007199254740993n也可以通过函数
BigInt
创建12345BigInt(123) // ==> 123nBigInt('123') // ==> 123nBigInt('0xFF') // ==> 255nBigInt('0b1101') // ==> 13nBigInt('0o777') // ==> 511nBigInt
仅接受整数或整数字符串1BigInt(123.45) // ==> RangeError
Promise.allSettled
示例
12345678Promise.allSettled([Promise.resolve('a'),Promise.reject('b'),]).then(arr => assert.deepEqual(arr, [{ status: 'fulfilled', value: 'a' },{ status: 'rejected', reason: 'b' },]))
String.prototype.matchAll()
globalThis
import.meta
The object import.meta holds metadata for the current module.
Dynamic imports via import()
Namespace re-exporting: export * as ns from 'mod'
示例
1234567891011121314// Named exportsexport function f() {}export const one = 1;export {foo, b as bar};// Default exportsexport default function f() {} // declaration with optional name// Replacement for `const` (there must be exactly one value)export default 123;// Re-exporting from another moduleexport {foo, b as bar} from './some-module.mjs';export * from './some-module.mjs';export * as ns from './some-module.mjs'; // ES2020
Related
¶