Skip to main content

no-for-in-array

禁止使用 for-in 循环对数组进行迭代.

💭

该规则需要 类型信息 才能运行,但这会带来性能方面的权衡。

for-in 循环 (for (const i in o)) 遍历对象的属性。虽然对数组值使用 for-in 循环是合法的,但并不常见。这有几个潜在的错误:

¥A for-in loop (for (const i in o)) iterates over the properties of an Object. While it is legal to use for-in loops with array values, it is not common. There are several potential bugs with this:

  1. 它迭代所有可枚举属性,包括非索引属性和整个原型链。例如,RegExp.prototype.exec 返回一个具有附加属性的数组,for-in 将对它们进行迭代。一些库甚至你自己的代码可能会向 Array.prototype 添加其他方法(作为 polyfill 或自定义方法),如果操作不当,它们也可能会被迭代。

    ¥It iterates over all enumerable properties, including non-index ones and the entire prototype chain. For example, RegExp.prototype.exec returns an array with additional properties, and for-in will iterate over them. Some libraries or even your own code may add additional methods to Array.prototype (either as polyfill or as custom methods), and if not done properly, they may be iterated over as well.

  2. 它会跳过数组中的漏洞。虽然稀疏数组很少见并且不建议使用,但它们仍然是可能的,并且你的代码应该能够处理它们。

    ¥It skips holes in the array. While sparse arrays are rare and advised against, they are still possible and your code should be able to handle them.

  3. "index" 以字符串而不是数字的形式返回。这可以被 TypeScript 捕获,但仍然可能导致微妙的错误。

    ¥The "index" is returned as a string, not a number. This can be caught by TypeScript, but can still lead to subtle bugs.

你可能混淆了 for-in 和 for-of,后者迭代数组的元素。如果你确实需要索引,请使用常规 for 循环或 forEach 方法。

¥You may have confused for-in with for-of, which iterates over the elements of the array. If you actually need the index, use a regular for loop or the forEach method.

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

在线运行试试这个规则 ↗

示例

¥Examples

declare const array: string[];

for (const i in array) {
console.log(array[i]);
}

for (const i in array) {
console.log(i, array[i]);
}
Open in Playground

选项

该规则不可配置。

何时不使用它

¥When Not To Use It

如果你的项目是一个罕见的故意循环数组字符串索引的项目,你可以关闭此规则。你可以考虑在这些特定情况下使用 ESLint 禁用注释,而不是完全禁用此规则。

¥If your project is a rare one that intentionally loops over string indices of arrays, you can turn off this rule. You might consider using ESLint disable comments for those specific situations instead of completely disabling this rule.


Type checked lint rules are more powerful than traditional lint rules, but also require configuring type checked linting.

See Troubleshooting > Linting with Type Information > Performance if you experience performance degradations after enabling type checked rules.

资源