blob: 06ce40ad0b84926487321208dfa765b83217217f (
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
|
---
title: 管道操作符
slug: Web/JavaScript/Reference/Operators/管道操作符
tags:
- Experimental
- JavaScript
- Operator
- 语法糖
- 链式
- 链式调用
translation_of: Web/JavaScript/Reference/Operators/Pipeline_operator
---
<div>{{jsSidebar("Operators")}} {{SeeCompatTable}}</div>
<p>试验性的管道操作符 <code>|></code> (目前其标准化流程处于 stage 1 阶段)允许以一种易读的方式去对函数链式调用。本质上来说,管道操作符是单参数函数调用的语法糖,它允许你像这样执行一个调用:</p>
<pre class="brush: js">let url = "%21" |> decodeURI;</pre>
<p>使用传统语法写的话,等效的代码是这样的:</p>
<pre class="brush: js">let url = decodeURI("%21");
</pre>
<h2 id="语法">语法</h2>
<pre class="syntaxbox">expression |> function</pre>
<h2 id="例子">例子</h2>
<h3 id="函数链式调用">函数链式调用</h3>
<p>当链式调用多个函数时,使用管道操作符可以改善代码的可读性。</p>
<pre class="brush: js">const double = (n) => n * 2;
const increment = (n) => n + 1;
// 没有用管道操作符
double(increment(double(5))); // 22
// 用上管道操作符之后
5 |> double |> increment |> double; // 22
</pre>
<h2 id="规范">规范</h2>
<table class="standard-table">
<thead>
<tr>
<th scope="col">规范</th>
<th scope="col">状态</th>
<th scope="col">备注</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="http://tc39.github.io/proposal-pipeline-operator/">Pipeline operator draft</a></td>
<td>Stage 1</td>
<td>Not part of the ECMAScript specification yet.</td>
</tr>
</tbody>
</table>
<h2 id="浏览器兼容性Edit">浏览器兼容性<a class="button section-edit only-icon" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators$edit#浏览器兼容性" rel="nofollow, noindex"><span>Edit</span></a></h2>
<div>
<p>{{Compat("javascript.operators.pipeline")}}</p>
</div>
<h2 id="参见">参见</h2>
<ul>
<li>GitHub 上的 <a href="https://github.com/tc39/proposals">TC39/proposals</a></li>
</ul>
|