blob: a97320ba3a3082c1b88ba4ccca5bfe3040267dad (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
---
title: 逻辑空赋值 (??=)
slug: Web/JavaScript/Reference/Operators/Logical_nullish_assignment
translation_of: Web/JavaScript/Reference/Operators/Logical_nullish_assignment
---
<div>{{jsSidebar("Operators")}}</div>
<p>逻辑空赋值运算符 (<code>x ??= y</code>) 仅在 <code>x</code> 是 {{Glossary("nullish")}} (<code>null</code> 或 <code>undefined</code>) 时对其赋值。</p>
<div>{{EmbedInteractiveExample("pages/js/expressions-logical-nullish-assignment.html")}}</div>
<h2 id="语法">语法</h2>
<pre class="syntaxbox"><em>expr1</em> ??= <em>expr2</em>
</pre>
<h2 id="描述">描述</h2>
<h3 id="语法短路求值">语法短路求值</h3>
<p><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator">空值合并</a>运算符从左至右求值,其使用以下规则测试是否可能进行语法短路求值:</p>
<p><code>(结果非 null 或 undefined 的表达式) ?? expr</code> 被短路求值为左侧表达式,当左侧证明为既非 <code>null</code> 也非 <code>undefined</code>.</p>
<p>语法短路意味着 <code><em>expr</em></code> 部分<strong>尚未被求值</strong>,因此任何与其求值产生的相关副作用都不会生效(例如,如果 <code><em>expr</em></code> 是一个函数调用,则该调用将不会发生)。</p>
<p>逻辑空赋值的语法短路也意味着 <code>x ??= y</code> 等价于:</p>
<pre class="brush: js">x ?? (x = y);</pre>
<p>而不等价于如下的表达式,因为其一定会发生赋值:</p>
<pre class="brush: js example-bad">x = x ?? y;
</pre>
<h2 id="例子">例子</h2>
<h3 id="使用逻辑空赋值">使用逻辑空赋值</h3>
<pre class="brush: js">function config(options) {
options.duration ??= 100;
options.speed ??= 25;
return options;
}
config({ duration: 125 }); // { duration: 125, speed: 25 }
config({}); // { duration: 100, speed: 25 }
</pre>
<h2 id="规范">规范</h2>
<table class="standard-table">
<thead>
<tr>
<th scope="col">规范</th>
</tr>
</thead>
<tbody>
<tr>
</tr>
<tr>
<td>{{SpecName('Logical Assignment', '#sec-assignment-operators', 'Assignment operators')}}</td>
</tr>
</tbody>
</table>
<h2 id="浏览器兼容性">浏览器兼容性</h2>
<p>{{Compat("javascript.operators.logical_nullish_assignment")}}</p>
<h2 id="相关链接">相关链接</h2>
<ul>
<li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator">The nullish coalescing operator (<code>??</code>)</a></li>
<li>{{Glossary("Nullish")}}</li>
<li>{{Glossary("Truthy")}}</li>
<li>{{Glossary("Falsy")}}</li>
</ul>
|