版本

no-cond-assign

不允許在條件表達式中使用賦值運算符

建議

設定檔中使用來自 @eslint/jsrecommended 設定會啟用此規則

在條件語句中,很容易將比較運算符(例如 ==)誤打成賦值運算符(例如 =)。例如

// Check the user's job title
if (user.jobTitle = "manager") {
    // user.jobTitle is now incorrect
}

在條件語句中使用賦值運算符是有正當理由的。但是,很難判斷特定的賦值是否有意為之。

規則詳情

此規則不允許在 ifforwhiledo...while 語句的測試條件中使用模稜兩可的賦值運算符。

選項

此規則有一個字串選項

  • "except-parens"(預設)允許在測試條件中賦值,僅當它們被括在括號中時(例如,允許在 whiledo...while 迴圈的測試中重新賦值變數)。
  • "always" 不允許在測試條件中進行任何賦值。

except-parens

使用預設 "except-parens" 選項時,此規則的錯誤程式碼範例

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

// Unintentional assignment
let x;
if (x = 0) {
    const b = 1;
}

// Practical example that is similar to an error
const setHeight = function (someNode) {
    do {
        someNode.height = "100px";
    } while (someNode = someNode.parentNode);
}

使用預設 "except-parens" 選項時,此規則的正確程式碼範例

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

// Assignment replaced by comparison
let x;
if (x === 0) {
    const b = 1;
}

// Practical example that wraps the assignment in parentheses
const setHeight = function (someNode) {
    do {
        someNode.height = "100px";
    } while ((someNode = someNode.parentNode));
}

// Practical example that wraps the assignment and tests for 'null'
const set_height = function (someNode) {
    do {
        someNode.height = "100px";
    } while ((someNode = someNode.parentNode) !== null);
}

always

使用 "always" 選項時,此規則的錯誤程式碼範例

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

// Unintentional assignment
let x;
if (x = 0) {
    const b = 1;
}

// Practical example that is similar to an error
const setHeight = function (someNode) {
    do {
        someNode.height = "100px";
    } while (someNode = someNode.parentNode);
}

// Practical example that wraps the assignment in parentheses
const set_height = function (someNode) {
    do {
        someNode.height = "100px";
    } while ((someNode = someNode.parentNode));
}

// Practical example that wraps the assignment and tests for 'null'
const heightSetter = function (someNode) {
    do {
        someNode.height = "100px";
    } while ((someNode = someNode.parentNode) !== null);
}

使用 "always" 選項時,此規則的正確程式碼範例

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

// Assignment replaced by comparison
let x;
if (x === 0) {
    const b = 1;
}

版本

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

資源

變更語言