Comma Operator
逗号操作符 对它的每个操作数求值(从左到右),并返回最后一个操作数的值。
语法
expr1, expr2, expr3...参数
expr1,expr2, expr3...任一表达式。
描述
当你想要在期望一个表达式的位置包含多个表达式时,可以使用逗号操作符。这个操作符最常用的一种情况是:for 循环中提供多个参数。
示例
假设a 是一个二维数组,每一维度包含10个元素,则下面的代码使用逗号操作符一次递增/递减两个变量。需要注意的是,var 语句中的逗号不是逗号操作符,因为它不是存在于一个表达式中。尽管从实际效果来看,那个逗号同逗号运算符的表现很相似。但确切地说,它是 var 语句中的一个特殊符号,用于把多个变量声明结合成一个。
下面的代码打印一个二维数组中斜线方向的元素:
for (var i = 0, j = 9; i <= 9; i++, j--)
  console.log('a[' + i + '][' + j + '] = ' + a[i][j]);请注意,诸如var语句之类的赋值中的逗号可能看起来没有逗号运算符的正常效果,因为它们不存在于表达式中。在下面的例子中,a被设置为b = 3(它是3)的值,但是c = 4表达式仍然计算并且其结果返回到控制台(即,4)。这是由于运算符的优先级和相关性。
// Note that the following creates globals and is disallowed in strict mode.
a = b = 3, c = 4; // Returns 4 in console
console.log(a); // 3 (left-most)
x = (y = 5, z = 6); // Returns 6 in console
console.log(x); // 6 (right-most)逗号运算符与数组,对象,函数参数和参数中的逗号完全不同。
处理然后返回
另一个可以用逗号运算符的例子是在返回之前处理。如上所述,只有最后一个元素将被返回,但所有其他元素也将被评估。所以,可以这样做:
function myFunc() {
  var x = 0;
  return (x += 1, x); // the same as return ++x;
}规范
| Specification | Status | Comment | 
|---|---|---|
| ECMAScript Latest Draft (ECMA-262)The definition of 'Comma operator' in that specification. | Living Standard |  | 
| ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'Comma operator' in that specification. | Standard |  | 
| ECMAScript 5.1 (ECMA-262)The definition of 'Comma operator' in that specification. | Standard |  | 
| ECMAScript 1st Edition (ECMA-262)The definition of 'Comma operator' in that specification. | Standard | Initial definition | 
浏览器兼容性
| Feature | Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari | 
|---|---|---|---|---|---|---|
| Basic support | (Yes) | (Yes) | (Yes) | 3.0 | (Yes) | (Yes) | 
| Feature | Android | Chrome for Android | Edge | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile | 
|---|---|---|---|---|---|---|---|
| Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | 
本文档系腾讯云开发者社区成员共同维护,如有问题请联系 cloudcommunity@tencent.com

