Movatterモバイル変換


[0]ホーム

URL:


  1. 面向开发者的 Web 技术
  2. JavaScript
  3. JavaScript 参考
  4. 表达式和运算符
  5. 逻辑与赋值(&&=)

此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in EnglishAlways switch to English

逻辑与赋值(&&=)

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值时为其赋值。

尝试一下

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);

如果左操作数不为真值,则由于逻辑与运算符的短路运算,不进行赋值操作。例如,由于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; // 0x &&= 1; // 0y &&= 1; // 1y &&= 0; // 0

规范

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

浏览器兼容性

参见

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp