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"
選項的錯誤程式碼範例
在遊樂場中開啟
/*eslint no-return-assign: "error"*/
function doSomething() {
}
function doSomethingElse() {
}
const foo =
const bar =
function doSomethingMore() {
}
預設 "except-parens"
選項的正確程式碼範例
在遊樂場中開啟
/*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"
選項的錯誤程式碼範例
在遊樂場中開啟
/*eslint no-return-assign: ["error", "always"]*/
function doSomething() {
}
function doSomethingElse() {
}
function doSomethingMore() {
}
"always"
選項的正確程式碼範例
在遊樂場中開啟
/*eslint no-return-assign: ["error", "always"]*/
function doSomething() {
return foo == bar + 2;
}
function doSomethingElse() {
return foo === bar + 2;
}
何時不該使用
如果您想允許在 return
陳述式中使用賦值運算子,則可以安全地停用此規則。
版本
此規則在 ESLint v0.0.9 中引入。