Skip to main content

prefer-for-of

Enforce the use of for-of loop over the standard for loop where possible.

🎨

ESLint 配置 中扩展"plugin:@typescript-eslint/stylistic" 可启用此规则。


许多开发者默认编写 for (let i = 0; i < ... 循环来迭代数组。 然而,在许多这样的数组中,循环迭代器变量(例如 i)仅用于访问数组的相应元素。 在这些情况下,for-of 循环更容易读写。

英:Many developers default to writing for (let i = 0; i < ... loops to iterate over arrays. However, in many of those arrays, the loop iterator variable (e.g. i) is only used to access the respective element of the array. In those cases, a for-of loop is easier to read and write.

当循环索引仅用于从正在迭代的数组中读取时,此规则建议使用 for-of 循环。

英:This rule recommends a for-of loop when the loop index is only used to read from an array that is being iterated.

.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/prefer-for-of": "error"
}
};
在线运行试试这个规则 ↗

示例

declare const array: string[];

for (let i = 0; i < array.length; i++) {
console.log(array[i]);
}
Open in Playground

选项

该规则不可配置。

资源