From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- .../logical_nullish_assignment/index.html | 82 ++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 files/zh-cn/web/javascript/reference/operators/logical_nullish_assignment/index.html (limited to 'files/zh-cn/web/javascript/reference/operators/logical_nullish_assignment') diff --git a/files/zh-cn/web/javascript/reference/operators/logical_nullish_assignment/index.html b/files/zh-cn/web/javascript/reference/operators/logical_nullish_assignment/index.html new file mode 100644 index 0000000000..a57c18e5c2 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/operators/logical_nullish_assignment/index.html @@ -0,0 +1,82 @@ +--- +title: 逻辑空赋值 (??=) +slug: Web/JavaScript/Reference/Operators/Logical_nullish_assignment +translation_of: Web/JavaScript/Reference/Operators/Logical_nullish_assignment +--- +
{{jsSidebar("Operators")}}
+ +

逻辑空赋值运算符 (x ??= y) 仅在 x 是 {{Glossary("nullish")}} (null 或 undefined) 时对其赋值。

+ +
{{EmbedInteractiveExample("pages/js/expressions-logical-nullish-assignment.html")}}
+ + + +

语法

+ +
expr1 ??= expr2
+
+ +

描述

+ +

语法短路求值

+ +

空值合并运算符从左至右求值,其使用以下规则测试是否可能进行语法短路求值:

+ +

(结果非 null 或 undefined 的表达式) ?? expr 被短路求值为左侧表达式,当左侧证明为既非 null 也非 undefined.

+ +

语法短路意味着 expr 部分尚未被求值,因此任何与其求值产生的相关副作用都不会生效(例如,如果 expr 是一个函数调用,则该调用将不会发生)。

+ +

逻辑空赋值的语法短路也意味着 x ??= y 等价于:

+ +
x ?? (x = y);
+ +

而不等价于如下的表达式,因为其一定会发生赋值:

+ +
x = x ?? y;
+
+ +

例子

+ +

使用逻辑空赋值

+ +
function config(options) {
+  options.duration ??= 100;
+  options.speed ??= 25;
+  return options;
+}
+
+config({ duration: 125 }); // { duration: 125, speed: 25 }
+config({}); // { duration: 100, speed: 25 }
+
+ +

规范

+ + + + + + + + + + + + + + +
规范
{{SpecName('Logical Assignment', '#sec-assignment-operators', 'Assignment operators')}}
+ +

浏览器兼容性

+ + + +

{{Compat("javascript.operators.logical_nullish_assignment")}}

+ +

相关链接

+ + -- cgit v1.2.3-54-g00ecf