版本

no-unmodified-loop-condition

禁止未修改的迴圈條件

迴圈條件中的變數通常在迴圈中被修改。如果沒有,則可能是錯誤。

while (node) {
    doSomething(node);
}
while (node) {
    doSomething(node);
    node = node.parent;
}

規則詳情

此規則查找迴圈條件內的引用,然後檢查這些引用的變數是否在迴圈中被修改。

如果引用在二元運算式或三元運算式中,此規則會檢查運算式的結果。如果引用在動態運算式(例如 CallExpressionYieldExpression、…)中,此規則會忽略它。

此規則的錯誤程式碼範例

在 Playground 中開啟
/*eslint no-unmodified-loop-condition: "error"*/

let node = something;

while (node) {
    doSomething(node);
}
node = other;

for (let j = 0; j < 5;) {
    doSomething(j);
}

while (node !== root) {
    doSomething(node);
}

此規則的正確程式碼範例

在 Playground 中開啟
/*eslint no-unmodified-loop-condition: "error"*/

while (node) {
    doSomething(node);
    node = node.parent;
}

for (let 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 中引入。

資源

變更語言