逻辑或赋值 (||=)

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

¥The logical OR assignment (||=) operator only evaluates the right operand and assigns to the left if the left operand is falsy.

Try it

语法

¥Syntax

js
x ||= y

描述

¥Description

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

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

js
const x = 1;
x ||= 2;

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

¥Neither would the following trigger the setter:

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

x.value ||= 2;

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

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

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

示例

¥Examples

设置默认内容

¥Setting default content

如果 "lyrics" 元素为空,则显示默认值:

¥If the "lyrics" element is empty, display a default value:

js
document.getElementById("lyrics").textContent ||= "No lyrics.";

在这里,短路特别有利,因为元素不会进行不必要的更新,也不会导致不需要的副作用,例如额外的解析或渲染工作,或失去焦点等。

¥Here the short-circuit is especially beneficial, since the element will not be updated unnecessarily and won't cause unwanted side-effects such as additional parsing or rendering work, or loss of focus, etc.

注意:请注意你要检查的 API 返回的值。如果返回空字符串(falsy 值),则必须使用 ||=,以便显示 "没有歌词。" 而不是空格。但是,如果 API 在内容为空的情况下返回 nullundefined,则应使用 ??=

¥Note: Pay attention to the value returned by the API you're checking against. If an empty string is returned (a falsy value), ||= must be used, so that "No lyrics." is displayed instead of a blank space. However, if the API returns null or undefined in case of blank content, ??= should be used instead.

规范

Specification
ECMAScript Language Specification
# sec-assignment-operators

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看