# comma-spacing
在逗号前后强制保持一致的间距
一些该规则报告的问题可以通过 --fix 命令行选项 自动修复
逗号周围的间距提高了项目列表的可读性。尽管大多数语言的样式指南都规定在逗号之后而不是之前添加空格,但这取决于项目的偏好。
var foo = 1, bar = 2;
var foo = 1 ,bar = 2;
# 规则详情
该规则在变量声明、数组字面量、对象字面量、函数参数和序列中强制逗号前后的间距保持一致。
本规则不适用于下列任何一种情况:
- 两个逗号之间
- 在左括号
[
和逗号之间,以避免与array-bracket-spacing
规则冲突 - 在逗号和右括号
]
之间,避免与array-bracket-spacing
规则冲突 - 在逗号和右大括号
}
之间,避免与object-curly-spacing
规则冲突 - 在逗号和右括号
)
之间,避免与space-in-parens
规则冲突
# 选项
此规则有一个对象选项:
"before": false
(默认)不允许逗号前有空格"before": true
在逗号前需要一个或多个空格"after": true
(默认)在逗号后需要一个或多个空格"after": false
不允许逗号后有空格
# after
带有默认 { "before": false, "after": true }
选项的此规则的错误代码示例:
/*eslint comma-spacing: ["error", { "before": false, "after": true }]*/
var foo = 1 ,bar = 2;
var arr = [1 , 2];
var obj = {"foo": "bar" ,"baz": "qur"};
foo(a ,b);
new Foo(a ,b);
function foo(a ,b){}
a ,b
带有默认 { "before": false, "after": true }
选项的此规则的正确代码示例:
/*eslint comma-spacing: ["error", { "before": false, "after": true }]*/
var foo = 1, bar = 2
, baz = 3;
var arr = [1, 2];
var arr = [1,, 3]
var obj = {"foo": "bar", "baz": "qur"};
foo(a, b);
new Foo(a, b);
function foo(a, b){}
a, b
带有默认 { "before": false, "after": true }
选项的此规则的正确代码的其他示例:
/*eslint comma-spacing: ["error", { "before": false, "after": true }]*/
// this rule does not enforce spacing between two commas
var arr = [
,,
, ,
];
// this rule does not enforce spacing after `[` and before `]`
var arr = [,];
var arr = [ , ];
var arr = [a, b,];
[,] = arr;
[ , ] = arr;
[a, b,] = arr;
// this rule does not enforce spacing before `}`
var obj = {x, y,};
var {z, q,} = obj;
import {foo, bar,} from "mod";
// this rule does not enforce spacing before `)`
foo(a, b,)
# before
此规则使用 { "before": true, "after": false }
选项的错误代码示例:
/*eslint comma-spacing: ["error", { "before": true, "after": false }]*/
var foo = 1, bar = 2;
var arr = [1 , 2];
var obj = {"foo": "bar", "baz": "qur"};
new Foo(a,b);
function foo(a,b){}
a, b
此规则使用 { "before": true, "after": false }
选项的正确代码示例:
/*eslint comma-spacing: ["error", { "before": true, "after": false }]*/
var foo = 1 ,bar = 2 ,
baz = true;
var arr = [1 ,2];
var arr = [1 ,,3]
var obj = {"foo": "bar" ,"baz": "qur"};
foo(a ,b);
new Foo(a ,b);
function foo(a ,b){}
a ,b
# 何时不使用
如果您的项目不会遵循一致的逗号间距模式,请关闭此规则。