no-cond-assign
不允許在條件表達式中使用賦值運算子
✅ 推薦
在設定檔中使用 @eslint/js
中的 recommended
設定會啟用此規則
在條件語句中,很容易將比較運算子(例如 ==
)誤打為賦值運算子(例如 =
)。例如
// Check the user's job title
if (user.jobTitle = "manager") {
// user.jobTitle is now incorrect
}
在條件語句中使用賦值運算子有其合理的理由。但是,很難判斷特定的賦值是否有意為之。
規則詳細資訊
此規則不允許在 if
、for
、while
和 do...while
語句的測試條件中使用不明確的賦值運算子。
選項
此規則有一個字串選項
"except-parens"
(預設)僅在測試條件被括在括號中時才允許賦值(例如,允許在while
或do...while
迴圈的測試中重新賦值變數)"always"
不允許在測試條件中進行任何賦值
except-parens
使用預設的 "except-parens"
選項時,此規則的錯誤程式碼範例
在遊樂場中開啟
/*eslint no-cond-assign: "error"*/
// Unintentional assignment
var x;
if () {
var b = 1;
}
// Practical example that is similar to an error
var setHeight = function (someNode) {
do {
someNode.height = "100px";
} while ();
}
使用預設的 "except-parens"
選項時,此規則的正確程式碼範例
在遊樂場中開啟
/*eslint no-cond-assign: "error"*/
// Assignment replaced by comparison
var x;
if (x === 0) {
var b = 1;
}
// Practical example that wraps the assignment in parentheses
var setHeight = function (someNode) {
do {
someNode.height = "100px";
} while ((someNode = someNode.parentNode));
}
// Practical example that wraps the assignment and tests for 'null'
var setHeight = function (someNode) {
do {
someNode.height = "100px";
} while ((someNode = someNode.parentNode) !== null);
}
always
使用 "always"
選項時,此規則的錯誤程式碼範例
在遊樂場中開啟
/*eslint no-cond-assign: ["error", "always"]*/
// Unintentional assignment
var x;
if () {
var b = 1;
}
// Practical example that is similar to an error
var setHeight = function (someNode) {
do {
someNode.height = "100px";
} while ();
}
// Practical example that wraps the assignment in parentheses
var setHeight = function (someNode) {
do {
someNode.height = "100px";
} while (());
}
// Practical example that wraps the assignment and tests for 'null'
var setHeight = function (someNode) {
do {
someNode.height = "100px";
} while (() !== null);
}
使用 "always"
選項時,此規則的正確程式碼範例
在遊樂場中開啟
/*eslint no-cond-assign: ["error", "always"]*/
// Assignment replaced by comparison
var x;
if (x === 0) {
var b = 1;
}
相關規則
版本
此規則是在 ESLint v0.0.9 中引入的。