版本

no-constant-condition

不允許在條件中使用常數表達式

推薦

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

常數表達式(例如,字面量)作為測試條件可能是輸入錯誤或用於觸發特定行為的開發用途。例如,以下程式碼看起來像是還沒準備好用於生產環境。

if (false) {
    doSomethingUnfinished();
}

規則詳情

此規則不允許在以下項目的測試條件中使用常數表達式:

  • ifforwhiledo...while 語句
  • ?: 三元表達式

此規則的 錯誤 程式碼範例

在遊樂場中開啟
/*eslint no-constant-condition: "error"*/

if (false) {
    doSomethingUnfinished();
}

if (void x) {
    doSomethingUnfinished();
}

if (x &&= false) {
    doSomethingNever();
}

if (class {}) {
    doSomethingAlways();
}

if (new Boolean(x)) {
    doSomethingAlways();
}

if (Boolean(1)) {
    doSomethingAlways();
}

if (undefined) {
    doSomethingUnfinished();
}

if (x ||= true) {
    doSomethingAlways();
}

for (;-2;) {
    doSomethingForever();
}

while (typeof x) {
    doSomethingForever();
}

do {
    doSomethingForever();
} while (x = -1);

const result = 0 ? a : b;

if(input === "hello" || "bye"){
  output(input);
}

此規則的 正確 程式碼範例

在遊樂場中開啟
/*eslint no-constant-condition: "error"*/

if (x === 0) {
    doSomething();
}

for (;;) {
    doSomethingForever();
}

while (typeof x === "undefined") {
    doSomething();
}

do {
    doSomething();
} while (x);

const result = x !== 0 ? a : b;

if(input === "hello" || input === "bye"){
  output(input);
}

選項

checkLoops

這是一個字串選項,具有以下值

  • "all" - 不允許在所有迴圈中使用常數表達式。
  • "allExceptWhileTrue" (預設) - 不允許在所有迴圈中使用常數表達式,但表達式為 truewhile 迴圈除外。
  • "none" - 允許在迴圈中使用常數表達式。

或者,您可以將 checkLoops 值設定為布林值,其中 true 等同於 "all",而 false 等同於 "none"

checkLoops"all"true 時的 錯誤 程式碼範例

在遊樂場中開啟
/*eslint no-constant-condition: ["error", { "checkLoops": "all" }]*/

while (true) {
    doSomething();
};

for (;true;) {
    doSomething();
};
在遊樂場中開啟
/*eslint no-constant-condition: ["error", { "checkLoops": true }]*/

while (true) {
    doSomething();
};

do {
    doSomething();
} while (true)

checkLoops"all"true 時的 正確 程式碼範例

在遊樂場中開啟
/*eslint no-constant-condition: ["error", { "checkLoops": "all" }]*/

while (a === b) {
    doSomething();
};
在遊樂場中開啟
/*eslint no-constant-condition: ["error", { "checkLoops": true }]*/

for (let x = 0; x <= 10; x++) {
    doSomething();
};

checkLoops"allExceptWhileTrue" 時的 正確 程式碼範例

在遊樂場中開啟
/*eslint no-constant-condition: "error"*/

while (true) {
    doSomething();
};

checkLoops"none"false 時的 正確 程式碼範例

在遊樂場中開啟
/*eslint no-constant-condition: ["error", { "checkLoops": "none" }]*/

while (true) {
    doSomething();
    if (condition()) {
        break;
    }
};

do {
    doSomething();
    if (condition()) {
        break;
    }
} while (true)
在遊樂場中開啟
/*eslint no-constant-condition: ["error", { "checkLoops": false }]*/

while (true) {
    doSomething();
    if (condition()) {
        break;
    }
};

for (;true;) {
    doSomething();
    if (condition()) {
        break;
    }
};

版本

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

資源

更改語言