跳至内容

@stylistic/js/

comma-spacing

逗号周围的空格可以提高项目列表的可读性。虽然大多数语言的样式指南都规定在逗号后添加空格,而不是在逗号前添加空格,但这取决于项目的偏好。

js
var foo = 1, bar = 2;
var foo = 1 ,bar = 2;

规则详情

此规则强制在变量声明、数组字面量、对象字面量、函数参数和序列中的逗号前后使用一致的空格。

此规则不适用于以下两种情况

选项

此规则有一个对象选项

  • "before": false (默认) 不允许逗号前有空格
  • "before": true 要求逗号前有一个或多个空格
  • "after": true (默认) 要求逗号后有一个或多个空格
  • "after": false 不允许逗号后有空格

after

使用默认 { "before": false, "after": true } 选项时,此规则的错误代码示例

js
/*eslint @stylistic/js/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 baz(a
,
b){}
a
,
b
incorrect

使用默认 { "before": false, "after": true } 选项时,此规则的正确代码示例

js
/*eslint @stylistic/js/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 qur(a, b){}
a, b
correct

使用默认 { "before": false, "after": true } 选项时,此规则的正确代码的其他示例

js
/*eslint @stylistic/js/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,)
correct

before

使用 { "before": true, "after": false } 选项时,此规则的错误代码示例

js
/*eslint @stylistic/js/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 baz(a
,
b){}
a
,
b
incorrect

使用 { "before": true, "after": false } 选项时,此规则的正确代码示例

js
/*eslint @stylistic/js/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 qur(a ,b){}
a ,b
correct

何时不使用它

如果您的项目不会遵循一致的逗号间距模式,请关闭此规则。