prefer-for-of
尽可能强制使用
for-of
循环而不是标准for
循环.
在 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.
- 扁平配置
- 旧版配置
export default tseslint.config({
rules: {
"@typescript-eslint/prefer-for-of": "error"
}
});
module.exports = {
"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 Playgrounddeclare const array: string[];
for (const x of array) {
console.log(x);
}
for (let i = 0; i < array.length; i++) {
// i is used, so for-of could not be used.
console.log(i, array[i]);
}
Open in PlaygroundDOM 元素
¥DOM Elements
默认情况下,TypeScript 的类型检查仅在启用 dom.iterable
lib
选项时才允许对 DOM 可 迭代对象(例如 HTMLCollectionOf
)进行 for-of
循环。如果你在处理 DOM 元素的项目中使用此规则,请确保在 TSConfig lib
中启用 dom.iterable
。有关更多信息,请参阅 aka.ms/tsconfig#lib。
¥By default, TypeScript's type checking only allows for-of
loops over DOM iterables such as HTMLCollectionOf
when the dom.iterable
lib
option is enabled.
If you are using this rule in a project that works with DOM elements, be sure to enable dom.iterable
in your TSConfig lib
.
See aka.ms/tsconfig#lib for more information.
{
"compilerOptions": {
"strict": true,
"lib": ["esnext", "dom", "dom.iterable"]
}
}
选项
该规则不可配置。
何时不使用它
¥When Not To Use It
请注意,此规则不使用类型信息来确定迭代元素是否为数组。它仅检查 .length
属性是否在循环中使用。如果你的项目循环遍历恰好包含 .length
的对象,则此规则可能会报告误报。你可以考虑在这些特定情况下使用 ESLint 禁用注释,而不是完全禁用此规则。
¥Note that this rule does not use type information to determine whether iterated elements are arrays.
It only checks if a .length
property is used in a loop.
If your project loops over objects that happen to have .length
, this rule may report false positives.
You might consider using ESLint disable comments for those specific situations instead of completely disabling this rule.