空合并赋值 (??=)

空值合并赋值 (??=) 运算符也称为逻辑空值赋值运算符,仅计算右操作数,如果左操作数为 nullishnullundefined),则分配给左操作数。

¥The nullish coalescing assignment (??=) operator, also known as the logical nullish assignment operator, only evaluates the right operand and assigns to the left if the left operand is nullish (null or undefined).

Try it

语法

¥Syntax

js
x ??= y

描述

¥Description

空合并赋值 short-circuits,意味着 x ??= y 等价于 x ?? (x = y),只不过表达式 x 仅计算一次。

¥Nullish coalescing assignment short-circuits, meaning that x ??= y is equivalent to x ?? (x = y), except that the expression x is only evaluated once.

如果由于 无效合并 运算符短路,左侧不为空,则不会执行任何分配。例如,尽管 xconst,但以下内容不会引发错误:

¥No assignment is performed if the left-hand side is not nullish, due to short-circuiting of the nullish coalescing operator. For example, the following does not throw an error, despite x being const:

js
const x = 1;
x ??= 2;

以下内容也不会触发设置器:

¥Neither would the following trigger the setter:

js
const x = {
  get value() {
    return 1;
  },
  set value(v) {
    console.log("Setter called");
  },
};

x.value ??= 2;

事实上,如果 x 不为 null,则根本不会评估 y

¥In fact, if x is not nullish, y is not evaluated at all.

js
const x = 1;
x ??= console.log("y evaluated");
// Logs nothing

示例

¥Examples

使用空值合并赋值

¥Using nullish coalescing assignment

你可以使用 nullish 合并赋值运算符将默认值应用于对象属性。与使用解构和 默认值 相比,如果属性的值为 null??= 也会应用默认值。

¥You can use the nullish coalescing assignment operator to apply default values to object properties. Compared to using destructuring and default values, ??= also applies the default value if the property has value null.

js
function config(options) {
  options.duration ??= 100;
  options.speed ??= 25;
  return options;
}

config({ duration: 125 }); // { duration: 125, speed: 25 }
config({}); // { duration: 100, speed: 25 }

规范

Specification
ECMAScript Language Specification
# sec-assignment-operators

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看