aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/javascript/reference/operators/comma_operator/index.html
blob: 1c9ca880542cf22eb1a54f79580940a936825154 (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
81
82
83
84
---
title: 逗号操作符
slug: Web/JavaScript/Reference/Operators/Comma_Operator
tags:
  - comma operator
  - 逗号操作符
translation_of: Web/JavaScript/Reference/Operators/Comma_Operator
---
<div>
<div>{{jsSidebar("Operators")}}</div>
</div>

<p><strong>逗号操作符 </strong> 对它的每个操作数求值(从左到右),并返回最后一个操作数的值。</p>

<p>{{EmbedInteractiveExample("pages/js/expressions-commaoperators.html")}}</p>

<h2 id="语法">语法</h2>

<pre class="syntaxbox"><em>expr1</em>, <em>expr2, expr3...</em></pre>

<h2 id="参数">参数</h2>

<dl>
 <dt><code>expr1</code>, <code>expr2, expr3...</code></dt>
 <dd>任一表达式。</dd>
</dl>

<h2 id="描述">描述</h2>

<p>当你想要在期望一个表达式的位置包含多个表达式时,可以使用逗号操作符。这个操作符最常用的一种情况是:<code>for</code> 循环中提供多个参数。</p>

<h2 id="示例">示例</h2>

<p>假设 <code>a</code> 是一个二维数组,每一维度包含10个元素,则下面的代码使用逗号操作符一次递增/递减两个变量。需要注意的是,<code>var</code> 语句中的逗号<em><strong>不是</strong></em>逗号操作符,因为它不是存在于一个表达式中。尽管从实际效果来看,那个逗号同逗号运算符的表现很相似。但确切地说,它是 <code>var</code> 语句中的一个特殊符号,用于把多个变量声明结合成一个。下面的代码打印一个二维数组中斜线方向的元素:</p>

<pre class="brush:js">for (var i = 0, j = 9; i &lt;= 9; i++, j--)
  document.writeln("a[" + i + "][" + j + "] = " + a[i][j]);</pre>

<h3 id="处理后返回">处理后返回</h3>

<p>另一个使用逗号操作符的例子是在返回值前处理一些操作。如同下面的代码,只有最后一个表达式被返回,其他的都只是被求值。</p>

<pre>function myFunc () {
  var x = 0;

  return (x += 1, x); // the same of return ++x;
}</pre>

<h2 id="规范">规范</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
  <tr>
   <td>ECMAScript 1st Edition.</td>
   <td>Standard</td>
   <td>Initial definition.</td>
  </tr>
  <tr>
   <td>{{SpecName('ES5.1', '#sec-11.14', 'Comma operator')}}</td>
   <td>{{Spec2('ES5.1')}}</td>
   <td> </td>
  </tr>
  <tr>
   <td>{{SpecName('ES6', '#sec-comma-operator', 'Comma operator')}}</td>
   <td>{{Spec2('ES6')}}</td>
   <td> </td>
  </tr>
 </tbody>
</table>

<h2 id="浏览器兼容性">浏览器兼容性</h2>

<p>{{Compat("javascript.operators.comma")}}</p>

<h2 id="See_also">参见</h2>

<ul>
 <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for">for loop</a></li>
</ul>