逻辑与赋值 (&&=)

逻辑 AND 赋值 (&&=) 运算符仅计算右操作数,如果左操作数为 truthy,则赋值给左操作数。

¥The logical AND assignment (&&=) operator only evaluates the right operand and assigns to the left if the left operand is truthy.

Try it

语法

¥Syntax

js
x &&= y

描述

¥Description

逻辑 AND 赋值 short-circuits,意味着 x &&= y 等价于 x && (x = y),只不过表达式 x 仅计算一次。

¥Logical AND 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 truthy, due to short-circuiting of the logical AND operator. For example, the following does not throw an error, despite x being const:

js
const x = 0;
x &&= 2;

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

¥Neither would the following trigger the setter:

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

x.value &&= 2;

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

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

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

示例

¥Examples

使用逻辑 AND 赋值

¥Using logical AND assignment

js
let x = 0;
let y = 1;

x &&= 0; // 0
x &&= 1; // 0
y &&= 1; // 1
y &&= 0; // 0

规范

Specification
ECMAScript Language Specification
# sec-assignment-operators

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看