no-unmodified-loop-condition
禁止未修改的迴圈條件
迴圈條件中的變數通常會在迴圈內被修改。如果沒有,這可能是一個錯誤。
while (node) {
doSomething(node);
}
while (node) {
doSomething(node);
node = node.parent;
}
規則詳情
此規則會找出迴圈條件內的參考,然後檢查這些參考的變數是否在迴圈內被修改。
如果參考在二元運算式或三元運算式內,此規則會檢查運算式的結果。如果參考在動態運算式內(例如 CallExpression
、YieldExpression
等),此規則會忽略它。
此規則的不正確程式碼範例
在線上編輯器中開啟
/*eslint no-unmodified-loop-condition: "error"*/
var node = something;
while () {
doSomething(node);
}
node = other;
for (var j = 0; < 5;) {
doSomething(j);
}
while ( !== root) {
doSomething(node);
}
此規則的正確程式碼範例
在線上編輯器中開啟
/*eslint no-unmodified-loop-condition: "error"*/
while (node) {
doSomething(node);
node = node.parent;
}
for (var j = 0; j < items.length; ++j) {
doSomething(items[j]);
}
// OK, the result of this binary expression is changed in this loop.
while (node !== root) {
doSomething(node);
node = node.parent;
}
// OK, the result of this ternary expression is changed in this loop.
while (node ? A : B) {
doSomething(node);
node = node.parent;
}
// A property might be a getter which has side effect...
// Or "doSomething" can modify "obj.foo".
while (obj.foo) {
doSomething(obj);
}
// A function call can return various values.
while (check(obj)) {
doSomething(obj);
}
何時不該使用
如果您不希望收到關於迴圈條件內參考的通知,那麼停用此規則是安全的。
版本
此規則是在 ESLint v2.0.0-alpha-2 中引入的。