此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。
逻辑与赋值(&&=)
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2020年9月.
逻辑与赋值(x &&= y)运算仅在x 为真值时为其赋值。
In this article
尝试一下
let a = 1;let b = 0;a &&= 2;console.log(a);// Expected output: 2b &&= 2;console.log(b);// Expected output: 0语法
js
expr1 &&= expr2描述
逻辑与的短路运算意味着x &&= y 与下式等价:
js
x && (x = y);如果左操作数不为真值,则由于逻辑与运算符的短路运算,不进行赋值操作。例如,由于x 为const(常量),以下式子不会抛出错误:
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; // 0x &&= 1; // 0y &&= 1; // 1y &&= 0; // 0规范
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-assignment-operators> |