尾随逗号

在向 JavaScript 代码添加新元素、参数或属性时,尾随逗号(有时称为 "最后的逗号")非常有用。如果要添加新属性,则可以添加新行,而无需修改之前的最后一行(如果该行已使用尾随逗号)。这使得版本控制差异更清晰,并且编辑代码可能不那么麻烦。

¥Trailing commas (sometimes called "final commas") can be useful when adding new elements, parameters, or properties to JavaScript code. If you want to add a new property, you can add a new line without modifying the previously last line if that line already uses a trailing comma. This makes version-control diffs cleaner and editing code might be less troublesome.

JavaScript 从一开始就允许在数组文字中使用尾随逗号。现在,对象字面量、函数参数、命名导入、命名导出等中也允许使用尾随逗号。

¥JavaScript has allowed trailing commas in array literals since the beginning. Trailing commas are now also allowed in object literals, function parameters, named imports, named exports, and more.

然而,JSON 不允许所有尾随逗号。

¥JSON, however, disallows all trailing commas.

描述

¥Description

只要接受逗号分隔的值列表,JavaScript 就允许使用尾随逗号,并且在最后一项之后可能会出现更多值。这包括:

¥JavaScript allows trailing commas wherever a comma-separated list of values is accepted and more values may be expected after the last item. This includes:

在所有这些情况下,尾随逗号完全是可选的,并且不会以任何方式改变程序的语义。

¥In all these cases, the trailing comma is entirely optional and doesn't change the program's semantics in any way.

在跨多行的列表中添加、删除或重新排序项目时,它特别有用,因为它减少了需要更改的行数,这有助于编辑和检查差异。

¥It is particular useful when adding, removing, or reordering items in a list that spans multiple lines, because it reduces the number of lines that need to be changed, which helps with both editing and reviewing the diff.

diff
  [
    "foo",
+   "baz",
    "bar",
-   "baz",
  ]

示例

¥Examples

文字中的尾随逗号

¥Trailing commas in literals

数组

¥Arrays

JavaScript 忽略数组文字中的尾随逗号:

¥JavaScript ignores trailing commas in arrays literals:

js
const arr = [
  1,
  2,
  3,
];

arr; // [1, 2, 3]
arr.length; // 3

如果使用多个尾随逗号,则会产生省略(或空洞)。有孔的数组称为 sparse(密集数组没有孔)。当使用 Array.prototype.forEach()Array.prototype.map() 迭代数组时,会跳过数组孔。稀疏数组通常是不利的,因此应避免使用多个尾随逗号。

¥If more than one trailing comma is used, an elision (or hole) is produced. An array with holes is called sparse (a dense array has no holes). When iterating arrays for example with Array.prototype.forEach() or Array.prototype.map(), array holes are skipped. Sparse arrays are generally unfavorable, so you should avoid having multiple trailing commas.

js
const arr = [1, 2, 3, , ,];
arr.length; // 5

对象

¥Objects

对象字面量中的尾随逗号也是合法的:

¥Trailing commas in object literals are legal as well:

js
const object = {
  foo: "bar",
  baz: "qwerty",
  age: 42,
};

函数中的尾随逗号

¥Trailing commas in functions

函数参数列表中也允许使用尾随逗号。

¥Trailing commas are also allowed in function parameter lists.

参数定义

¥Parameter definitions

以下函数定义对是合法的并且彼此等效。尾随逗号不会影响函数声明的 length 属性或其 arguments 对象。

¥The following function definition pairs are legal and equivalent to each other. Trailing commas don't affect the length property of function declarations or their arguments object.

js
function f(p) {}
function f(p,) {}

(p) => {};
(p,) => {};

尾随逗号也适用于类或对象的 方法定义

¥The trailing comma also works with method definitions for classes or objects:

js
class C {
  one(a,) {}
  two(a, b,) {}
}

const obj = {
  one(a,) {},
  two(a, b,) {},
};

函数调用

¥Function calls

以下函数调用对是合法的并且彼此等效。

¥The following function invocation pairs are legal and equivalent to each other.

js
f(p);
f(p,);

Math.max(10, 20);
Math.max(10, 20,);

非法尾随逗号

¥Illegal trailing commas

仅包含逗号的函数参数定义或函数调用将抛出 SyntaxError。此外,使用 其余参数 时,不允许使用尾随逗号:

¥Function parameter definitions or function invocations only containing a comma will throw a SyntaxError. Furthermore, when using rest parameters, trailing commas are not allowed:

js
function f(,) {} // SyntaxError: missing formal parameter
(,) => {};       // SyntaxError: expected expression, got ','
f(,)             // SyntaxError: expected expression, got ','

function f(...p,) {} // SyntaxError: parameter after rest parameter
(...p,) => {}        // SyntaxError: expected closing parenthesis, got ','

解构中的尾随逗号

¥Trailing commas in destructuring

使用 解构赋值 时,左侧也允许有尾随逗号:

¥A trailing comma is also allowed on the left-hand side when using destructuring assignment:

js
// array destructuring with trailing comma
[a, b,] = [1, 2];

// object destructuring with trailing comma
const o = {
  p: 42,
  q: true,
};
const { p, q, } = o;

同样,当使用剩余元素时,将抛出 SyntaxError

¥Again, when using a rest element, a SyntaxError will be thrown:

js
const [a, ...b,] = [1, 2, 3];
// SyntaxError: rest element may not have a trailing comma

JSON 中的尾随逗号

¥Trailing commas in JSON

由于 JSON 基于 JavaScript 语法的一个非常受限制的子集,因此 JSON 中不允许使用尾随逗号。

¥As JSON is based on a very restricted subset of JavaScript syntax, trailing commas are not allowed in JSON.

这两行都会抛出 SyntaxError

¥Both lines will throw a SyntaxError:

js
JSON.parse("[1, 2, 3, 4, ]");
JSON.parse('{"foo" : 1, }');
// SyntaxError JSON.parse: unexpected character
// at line 1 column 14 of the JSON data

省略尾随逗号以正确解析 JSON:

¥Omit the trailing commas to parse the JSON correctly:

js
JSON.parse("[1, 2, 3, 4 ]");
JSON.parse('{"foo" : 1 }');

命名导入和命名导出中的尾随逗号

¥Trailing commas in named imports and named exports

尾随逗号在 命名导入命名导出 中有效。

¥Trailing commas are valid in named imports and named exports.

命名导入

¥Named imports

js
import {
  A,
  B,
  C,
} from "D";

import { X, Y, Z, } from "W";

import { A as B, C as D, E as F, } from "Z";

命名导出

¥Named exports

js
export {
  A,
  B,
  C,
};

export { A, B, C, };

export { A as B, C as D, E as F, };

量词前缀

¥Quantifier prefix

注意:quantifier 中的尾随逗号实际上将其语义从匹配“恰好 n”更改为匹配“至少 n”。

¥Note: The trailing comma in a quantifier actually changes its semantics from matching "exactly n" to matching "at least n".

js
/x{2}/; // Exactly 2 occurrences of "x"; equivalent to /xx/
/x{2,}/; // At least 2 occurrences of "x"; equivalent to /xx+/
/x{2,4}/; // 2 to 4 occurrences of "x"; equivalent to /xxx?x?/

规范

Specification
ECMAScript Language Specification
# prod-Elision
ECMAScript Language Specification
# prod-ObjectLiteral
ECMAScript Language Specification
# prod-ArrayLiteral
ECMAScript Language Specification
# prod-Arguments
ECMAScript Language Specification
# prod-FormalParameters
ECMAScript Language Specification
# prod-CoverParenthesizedExpressionAndArrowParameterList
ECMAScript Language Specification
# prod-NamedImports
ECMAScript Language Specification
# prod-NamedExports
ECMAScript Language Specification
# prod-QuantifierPrefix
ECMAScript Language Specification
# prod-annexB-InvalidBracedQuantifier

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看

¥See also