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.
此规则的错误代码示例:
¥Examples of incorrect code for this rule:
/*eslint for-direction: "error"*/
for (var i = 0; i < 10; i--) {
}
for (var i = 10; i >= 0; i++) {
}
for (var i = 0; i > 10; i++) {
}
for (var 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 (var i = 0; i < 10; i++) {
}
for (var 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
}
版本
此规则是在 ESLint v4.0.0-beta.0 中引入。