for-direction
强制 for 循环更新子句将计数器移向正确方向
在 配置文件 中使用来自 @eslint/js 的 recommended 配置可以启用此规则
一个具有永远无法达到的停止条件的 for 循环,例如计数器朝错误方向移动的循环,将会无限运行。虽然有些情况下无限循环是有意为之,但惯例是将此类循环构建为 while 循环。更常见的是,一个无限的 for 循环是一种错误。
🌐 A for loop with a stop condition that can never be reached, such as one with a counter that moves in the wrong direction, will run infinitely. While there are occasions when an infinite loop is intended, the convention is to construct such loops as while loops. More typically, an infinite for loop is a bug.
规则详情
🌐 Rule Details
此规则禁止 for 循环,其中计数器变量的变化方式导致终止条件永远不会满足。例如,如果计数器变量在增加(即 i++),而终止条件测试计数器是否大于零(i >= 0),则循环永远不会退出。
🌐 This rule forbids for loops where the counter variable changes in such a way that the stop condition will never be met. For example, if the counter variable is increasing (i.e. i++) and the stop condition tests that the counter is greater than zero (i >= 0) then the loop will never exit.
注意: 该规则仅检查计数器相对于停止条件的方向。它不会检查实际值来确定循环是否至少执行一次。例如,像
for (let i = 0; i < 0; i++) {}这样的循环被此规则认为是有效的,因为计数器方向(i++)与条件(i <)匹配,即使从一开始条件就是假的(死代码)。
此规则的错误代码示例:
🌐 Examples of incorrect code for this rule:
/*eslint for-direction: "error"*/
for (let i = 0; i < 10; i--) {
}
for (let i = 10; i >= 0; i++) {
}
for (let i = 0; i > 10; i++) {
// counter i is on the left with >, so i++ (increasing) is the wrong direction
}
for (let i = 0; i > 0; i++) {
// counter i is on the left with >, so i++ (increasing) is the wrong direction
}
for (let i = 0; 0 < i; i++) {
// counter i is on the right with <, so i++ (increasing) is the wrong direction
}
for (let i = 0; 10 > i; i--) {
}
const n = -2;
for (let i = 0; i < 10; i += n) {
}
符合此规则的正确代码示例:
🌐 Examples of correct code for this rule:
/*eslint for-direction: "error"*/
for (let i = 0; i < 10; i++) {
}
for (let i = 0; 10 > i; i++) { // with counter "i" on the right
}
for (let i = 10; i >= 0; i += this.step) { // direction unknown
}
for (let i = MIN; i <= MAX; i -= 0) { // not increasing or decreasing
}
for (let i = 0; i < 0; i++) {
// counter i is on the left with <, so i++ (increasing) is the correct direction
// (loop never executes, but direction is consistent)
}
for (let i = 0; 0 > i; i++) {
// counter i is on the right with >, so i++ (increasing) is the correct direction
// (loop never executes, but direction is consistent)
}
选项
🌐 Options
此规则没有选项。
🌐 This rule has no options.
版本
此规则是在 ESLint v4.0.0-beta.0 中引入。