no-unmodified-loop-condition

禁止未修改的循环条件

循环条件中的变量经常在循环中被修改。如果不是,那可能是一个错误。

¥Variables in a loop condition often are modified in the loop. If not, it’s possibly a mistake.

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

规则详情

¥Rule Details

此规则查找循环条件内的引用,然后检查这些引用的变量在循环中是否被修改。

¥This rule finds references which are inside of loop conditions, then checks the variables of those references are modified in the loop.

如果引用在二元表达式或三元表达式内,则此规则检查表达式的结果。如果引用在动态表达式中(例如 CallExpressionYieldExpression、…),则此规则将忽略它。

¥If a reference is inside of a binary expression or a ternary expression, this rule checks the result of the expression instead. If a reference is inside of a dynamic expression (e.g. CallExpression, YieldExpression, …), this rule ignores it.

此规则的错误代码示例:

¥Examples of incorrect code for this rule:

在线运行
/*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);
}

此规则的正确代码示例:

¥Examples of correct code for this rule:

在线运行
/*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);
}

何时不使用

¥When Not To Use It

如果你不想通知循环条件内的引用,那么禁用此规则是安全的。

¥If you don’t want to notified about references inside of loop conditions, then it’s safe to disable this rule.

版本

此规则是在 ESLint v2.0.0-alpha-2 中引入。

资源