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.

此规则建议明确初始化每个 成员值。

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

eslint.config.mjs
export default tseslint.config({
rules: {
"@typescript-eslint/prefer-for-of": "error"
}
});

在线运行试试这个规则 ↗

示例

¥Examples

declare const array: string[];

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

选项

该规则不可配置。

'## 资源'