🔖 javascriptecmascript

?. 操作符

?. 是链式调用操作符,当操作符左侧变量不存在时会返回 undefined,并中断链式调用。其英文名称为 Optional chaining for property accesses and method calls

  • Demo

    1
    2
    3
    o?.prop
    o?.['prop']
    f?.(arg1, arg2)

    等价于

    1
    2
    3
    (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 异常;因为此操作符的设计目的是容忍刻意的省略,因此对于类型错误应该抛出异常,而不是忽略它。

  • 对于带有 ?. 的链式调用,当中间路径不存在时,中间的函数调用不会得到执行,如:

    1
    2
    3
    4
    5
    6
    7
    8
    function isInvoked(obj) {
    let invoked = false;
    obj?.a.b.m(invoked = true);
    return invoked;
    }
    isInvoked({a: {b: {m() {}}}}) // => true
    isInvoked(undefined) {}}}}) // => false

?? 操作符

?? 操作符类似 ||,只不过其中断条件为非 nullundefined 值,而 || 中断条件为任意 Truthy 的值。其英文名称为 Nullish coalescing operator

  • 示例

    1
    a ?? b

    等价于

    1
    (a !== undefined && a !== null) ? a : b
  • 短路赋值用法(ES2021): a ??= b 等价于 a ?? (a = b)

BigInt

  • n 结尾的数字会自动转成 BigInt

    1
    2n**53n + 1n // => 9007199254740993n
  • 也可以通过函数 BigInt 创建

    1
    2
    3
    4
    5
    BigInt(123) // ==> 123n
    BigInt('123') // ==> 123n
    BigInt('0xFF') // ==> 255n
    BigInt('0b1101') // ==> 13n
    BigInt('0o777') // ==> 511n
  • BigInt 仅接受整数或整数字符串

    1
    BigInt(123.45) // ==> RangeError

Promise.allSettled

  • 示例

    1
    2
    3
    4
    5
    6
    7
    8
    Promise.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'

  • 示例

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    // Named exports
    export function f() {}
    export const one = 1;
    export {foo, b as bar};
    // Default exports
    export default function f() {} // declaration with optional name
    // Replacement for `const` (there must be exactly one value)
    export default 123;
    // Re-exporting from another module
    export {foo, b as bar} from './some-module.mjs';
    export * from './some-module.mjs';
    export * as ns from './some-module.mjs'; // ES2020
© 2017-2025 光和尘有花满渚、有酒盈瓯

Comments