逻辑与赋值(&&=)

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2020.

逻辑与赋值x &&= y)运算仅在 x值时为其赋值。

尝试一下

let a = 1;
let b = 0;

a &&= 2;
console.log(a);
// Expected output: 2

b &&= 2;
console.log(b);
// Expected output: 0

语法

js
expr1 &&= expr2

描述

逻辑与的短路运算意味着 x &&= y 与下式等价:

js
x && (x = y);

如果左操作数不为真值,则由于逻辑与运算符的短路运算,不进行赋值操作。例如,由于 xconst(常量),以下式子不会抛出错误:

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

也不会触发 setter 函数:

js
const x = {
  get value() {
    return 0;
  },
  set value(v) {
    console.log("调用了 setter");
  },
};
x.value &&= 2;

实际上,如果 x 不为真值,则根本不会对 y 求值。

js
const x = 0;
x &&= console.log("y 进行了求值");
// 什么都不会输出

示例

使用逻辑与赋值

js
let x = 0;
let y = 1;

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

规范

Specification
ECMAScript® 2025 Language Specification
# sec-assignment-operators

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
Logical AND assignment (x &&= y)

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

参见