版本

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);

var 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);

var 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 中引入。

資源

變更語言