no-constant-condition
禁止在條件中使用常數表達式
✅ 建議
在設定檔中使用 @eslint/js
的 recommended
設定會啟用此規則
常數表達式 (例如,字面值) 作為測試條件可能是打字錯誤或特定行為的開發觸發器。例如,以下程式碼看起來好像還沒準備好用於生產。
if (false) {
doSomethingUnfinished();
}
規則細節
此規則禁止在以下條件的測試條件中使用常數表達式
if
、for
、while
或do...while
語句?:
三元表達式
此規則的不正確程式碼範例
在線上遊樂場中開啟
/*eslint no-constant-condition: "error"*/
if () {
doSomethingUnfinished();
}
if () {
doSomethingUnfinished();
}
if () {
doSomethingNever();
}
if () {
doSomethingAlways();
}
if () {
doSomethingAlways();
}
if () {
doSomethingAlways();
}
if () {
doSomethingUnfinished();
}
if () {
doSomethingAlways();
}
for (;;) {
doSomethingForever();
}
while () {
doSomethingForever();
}
do {
doSomethingForever();
} while ();
var result = ? a : b;
if(){
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"
(預設) - 禁止在除了表達式為true
的while
迴圈之外的所有迴圈中使用常數表達式。"none"
- 允許在迴圈中使用常數表達式。
或者您可以將 checkLoops
值設定為布林值,其中 true
等同於 "all"
,而 false
等同於 "none"
。
當 checkLoops
為 "all"
或 true
時的不正確程式碼範例
在線上遊樂場中開啟
/*eslint no-constant-condition: ["error", { "checkLoops": "all" }]*/
while () {
doSomething();
};
for (;;) {
doSomething();
};
在線上遊樂場中開啟
/*eslint no-constant-condition: ["error", { "checkLoops": true }]*/
while () {
doSomething();
};
do {
doSomething();
} while ()
當 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 中引入。