版本

no-return-assign

禁止在 return 陳述式中使用賦值運算子

JavaScript 有趣且有時令人困惑的方面之一是賦值幾乎可以在任何時候發生。正因如此,一個錯誤的等號最終可能會導致賦值,而真正的意圖是進行比較。當使用 return 陳述式時尤其如此。例如

function doSomething() {
    return foo = bar + 2;
}

這裡很難判斷 return 陳述式的意圖。 函數可能旨在返回 bar + 2 的結果,但那為何又要賦值給 foo 呢? 也有可能意圖是使用比較運算子(例如 ==),而這段程式碼是一個錯誤。

由於這種模糊性,不建議在 return 陳述式中使用賦值被認為是一種最佳實務。

規則細節

此規則旨在消除 return 陳述式中的賦值。 因此,每當在 return 中找到賦值時,它都會發出警告。

選項

此規則接受一個選項,一個字串,其中必須包含以下值之一

  • except-parens (預設):除非賦值包含在括號中,否則不允許賦值。
  • always:禁止所有賦值。

except-parens

這是預設選項。 它不允許賦值,除非它們包含在括號中。

針對預設 "except-parens" 選項的不正確程式碼範例

在 Playground 中開啟
/*eslint no-return-assign: "error"*/

function doSomething() {
    return foo = bar + 2;
}

function doSomethingElse() {
    return foo += 2;
}

const foo = (a, b) => a = b

const bar = (a, b, c) => (a = b, c == b)

function doSomethingMore() {
    return foo = bar && foo > 0;
}

針對預設 "except-parens" 選項的正確程式碼範例

在 Playground 中開啟
/*eslint no-return-assign: "error"*/

function doSomething() {
    return foo == bar + 2;
}

function doSomethingElse() {
    return foo === bar + 2;
}

function doSomethingMore() {
    return (foo = bar + 2);
}

const foo = (a, b) => (a = b)

const bar = (a, b, c) => ((a = b), c == b)

function doAnotherThing() {
    return (foo = bar) && foo > 0;
}

always

此選項禁止在 return 陳述式中進行所有賦值。 所有賦值都被視為問題。

針對 "always" 選項的不正確程式碼範例

在 Playground 中開啟
/*eslint no-return-assign: ["error", "always"]*/

function doSomething() {
    return foo = bar + 2;
}

function doSomethingElse() {
    return foo += 2;
}

function doSomethingMore() {
    return (foo = bar + 2);
}

針對 "always" 選項的正確程式碼範例

在 Playground 中開啟
/*eslint no-return-assign: ["error", "always"]*/

function doSomething() {
    return foo == bar + 2;
}

function doSomethingElse() {
    return foo === bar + 2;
}

何時不該使用它

如果您想允許在 return 陳述式中使用賦值運算子,那麼您可以安全地停用此規則。

版本

此規則在 ESLint v0.0.9 中引入。

資源

變更語言