A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Logical_AND_assignment below:

逻辑与赋值(&&=) - JavaScript | MDN

逻辑与赋值(&&=)

Baseline Widely available

逻辑与赋值(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
语法 描述

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

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

也不会触发 setter 函数:

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

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

const x = 0;
x &&= console.log("y 进行了求值");
// 什么都不会输出
示例 使用逻辑与赋值
let x = 0;
let y = 1;

x &&= 0; // 0
x &&= 1; // 0
y &&= 1; // 1
y &&= 0; // 0
规范 浏览器兼容性 参见

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4