空合并运算符 (??)
空合并 (??
) 运算符是一个逻辑运算符,当其左侧操作数为 null
或 undefined
时,它返回其右侧操作数,否则返回其左侧操作数。
¥The nullish coalescing (??
) operator is a logical
operator that returns its right-hand side operand when its left-hand side operand is
null
or undefined
, and otherwise returns its left-hand side
operand.
Try it
语法
描述
¥Description
空值合并运算符可以看作 逻辑或 (||
) 运算符 的一个特例。如果左侧操作数是任意 falsy 值,而不仅仅是 null
或 undefined
,则后者返回右侧操作数。换句话说,如果你使用 ||
为另一个变量 foo
提供一些默认值,并且你认为某些虚假值可用(例如 ''
或 0
),则可能会遇到意外行为。更多示例请参见 below。
¥The nullish coalescing operator can be seen as a special case of the logical OR (||
) operator. The latter returns the right-hand side operand if the left operand is any falsy value, not only null
or undefined
. In other words, if you use ||
to provide some default value to another variable foo
, you may encounter unexpected behaviors if you consider some falsy values as usable (e.g., ''
or 0
). See below for more examples.
零合并运算符具有第五低的 运算符优先级,直接低于 ||
并直接高于 条件(三元)运算符。
¥The nullish coalescing operator has the fifth-lowest operator precedence, directly lower than ||
and directly higher than the conditional (ternary) operator.
无法将 AND (&&
) 和 OR 运算符 (||
) 直接与 ??
组合。在这种情况下将抛出 语法错误。
¥It is not possible to combine both the AND (&&
) and OR operators (||
) directly with ??
. A syntax error will be thrown in such cases.
null || undefined ?? "foo"; // raises a SyntaxError
true && undefined ?? "foo"; // raises a SyntaxError
相反,提供括号来明确指示优先级:
¥Instead, provide parenthesis to explicitly indicate precedence:
(null || undefined) ?? "foo"; // returns "foo"
示例
使用空值合并运算符
¥Using the nullish coalescing operator
在此示例中,我们将提供默认值,但保留 null
或 undefined
以外的值。
¥In this example, we will provide default values but keep values other than null
or undefined
.
const nullValue = null;
const emptyText = ""; // falsy
const someNumber = 42;
const valA = nullValue ?? "default for A";
const valB = emptyText ?? "default for B";
const valC = someNumber ?? 0;
console.log(valA); // "default for A"
console.log(valB); // "" (as the empty string is not null or undefined)
console.log(valC); // 42
为变量分配默认值
¥Assigning a default value to a variable
早些时候,当人们想要为变量分配默认值时,常见的模式是使用逻辑 OR 运算符 (||
):
¥Earlier, when one wanted to assign a default value to a variable, a common pattern was to use the logical OR operator (||
):
let foo;
// foo is never assigned any value so it is still undefined
const someDummyText = foo || "Hello!";
然而,由于 ||
是布尔逻辑运算符,左侧操作数被强制转换为布尔值进行求值,并且不会返回任何虚假值(包括 0
、''
、NaN
、false
等)。如果你将 0
、''
或 NaN
视为有效值,此行为可能会导致意外后果。
¥However, due to ||
being a boolean logical operator, the left-hand-side operand was coerced to a boolean for the evaluation and any falsy value (including 0
, ''
, NaN
, false
, etc.) was not returned. This behavior may cause unexpected consequences if you consider 0
, ''
, or NaN
as valid values.
const count = 0;
const text = "";
const qty = count || 42;
const message = text || "hi!";
console.log(qty); // 42 and not 0
console.log(message); // "hi!" and not ""
空合并运算符通过仅在第一个操作数计算为 null
或 undefined
(但没有其他虚假值)时返回第二个操作数来避免此陷阱:
¥The nullish coalescing operator avoids this pitfall by only returning the second operand when the first one evaluates to either null
or undefined
(but no other falsy values):
const myText = ""; // An empty string (which is also a falsy value)
const notFalsyText = myText || "Hello world";
console.log(notFalsyText); // Hello world
const preservingFalsy = myText ?? "Hi neighborhood";
console.log(preservingFalsy); // '' (as myText is neither undefined nor null)
短路
¥Short-circuiting
与 OR 和 AND 逻辑运算符一样,如果左侧表达式既不是 null
也不是 undefined
,则不会评估右侧表达式。
¥Like the OR and AND logical operators, the right-hand side expression is not evaluated if the left-hand side proves to be neither null
nor undefined
.
function a() {
console.log("a was called");
return undefined;
}
function b() {
console.log("b was called");
return false;
}
function c() {
console.log("c was called");
return "foo";
}
console.log(a() ?? c());
// Logs "a was called" then "c was called" and then "foo"
// as a() returned undefined so both expressions are evaluated
console.log(b() ?? c());
// Logs "b was called" then "false"
// as b() returned false (and not null or undefined), the right
// hand side expression was not evaluated
与可选链运算符 (?.) 的关系
¥Relationship with the optional chaining operator (?.)
空合并运算符将 undefined
和 null
视为特定值。可选链接运算符 (?.
) 也是如此,它对于访问可能是 null
或 undefined
的对象的属性很有用。将它们结合起来,你可以安全地访问对象的属性,该属性可能为空,并提供默认值(如果是)。
¥The nullish coalescing operator treats undefined
and null
as specific values. So does the optional chaining operator (?.
), which is useful to access a property of an object which may be null
or undefined
. Combining them, you can safely access a property of an object which may be nullish and provide a default value if it is.
const foo = { someFooProp: "hi" };
console.log(foo.someFooProp?.toUpperCase() ?? "not available"); // "HI"
console.log(foo.someBarProp?.toUpperCase() ?? "not available"); // "not available"
规范
Specification |
---|
ECMAScript Language Specification # prod-CoalesceExpression |
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also