no-sequences
禁止使用逗號運算子
逗號運算子包含多個運算式,但只預期一個。它從左到右評估每個運算元,並傳回最後一個運算元的值。然而,這經常模糊了副作用,而且它的使用往往是意外。以下是一些序列的範例
var a = (3, 5); // a = 5
a = b += 5, a + b;
while (a = next(), a && a.length);
(0, eval)("doSomething();");
規則詳細資訊
此規則禁止使用逗號運算子,但以下例外
- 在
for
語句的初始化或更新部分。 - 預設情況下,如果運算式序列明確地包在括號中。可以使用
allowInParentheses
選項移除此例外。
此規則的錯誤程式碼範例
在遊樂場開啟
/*eslint no-sequences: "error"*/
foo = doSomething() val;
0 eval("doSomething();");
do {} while (doSomething() !!test);
for (; doSomething() !!test; );
if (doSomething() !!test);
switch (val = foo() val) {}
while (val = foo() val < 42);
with (doSomething() val) {}
此規則的正確程式碼範例
在遊樂場開啟
/*eslint no-sequences: "error"*/
foo = (doSomething(), val);
(0, eval)("doSomething();");
do {} while ((doSomething(), !!test));
for (i = 0, j = 10; i < j; i++, j--);
if ((doSomething(), !!test));
switch ((val = foo(), val)) {}
while ((val = foo(), val < 42));
with ((doSomething(), val)) {}
關於箭頭函式主體的注意事項
如果箭頭函式主體是一個語句而不是一個區塊,並且該語句包含一個序列,您需要在語句周圍使用雙括號來表示該序列是故意的。
箭頭函式的錯誤程式碼範例
在遊樂場開啟
/*eslint no-sequences: "error"*/
const foo = (val) => (console.log('bar') val);
const baz = () => ((bar = 123) 10);
const qux = () => { return (bar = 123) 10 }
箭頭函式的正確程式碼範例
在遊樂場開啟
/*eslint no-sequences: "error"*/
const foo = (val) => ((console.log('bar'), val));
const baz = () => (((bar = 123), 10));
const qux = () => { return ((bar = 123), 10) }
選項
此規則採用一個選項,即一個物件,具有以下屬性
"allowInParentheses"
:如果設定為true
(預設),此規則允許明確地包在括號中的運算式序列。
allowInParentheses
使用 { "allowInParentheses": false }
選項時,此規則的錯誤程式碼範例
在遊樂場開啟
/*eslint no-sequences: ["error", { "allowInParentheses": false }]*/
foo = (doSomething() val);
(0 eval)("doSomething();");
do {} while ((doSomething() !!test));
for (; (doSomething() !!test); );
if ((doSomething() !!test));
switch ((val = foo() val)) {}
while ((val = foo() val < 42));
with ((doSomething() val)) {}
const foo = (val) => ((console.log('bar') val));
使用 { "allowInParentheses": false }
選項時,此規則的正確程式碼範例
在遊樂場開啟
/*eslint no-sequences: ["error", { "allowInParentheses": false }]*/
for (i = 0, j = 10; i < j; i++, j--);
何時不該使用它
如果接受帶有逗號運算子的序列運算式,請停用此規則。另一種情況是您可能想要報告逗號運算子的所有用法,即使在 for 迴圈中也是如此。您可以使用規則 no-restricted-syntax
來實現此目的
{
"rules": {
"no-restricted-syntax": ["error", "SequenceExpression"]
}
}
版本
此規則是在 ESLint v0.5.1 中引入的。