noForIn
¥Summary
-
规则生效日期:
v2.3.6¥Rule available since:
v2.3.6 -
诊断类别:
lint/nursery/noForIn¥Diagnostic Category:
lint/nursery/noForIn -
此规则没有修复方案。
¥This rule doesn’t have a fix.
-
此规则的默认严重级别为 information。
¥The default severity of this rule is information.
-
来源:
¥Sources:
-
灵感来自
@typescript-eslint/no-for-in-array¥Inspired from
@typescript-eslint/no-for-in-array
-
¥How to configure
{ "linter": { "rules": { "nursery": { "noForIn": "error" } } }}¥Description
禁止使用 for-in 循环进行迭代。
¥Disallow iterating using a for-in loop.
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:
-
它会遍历所有可枚举属性,包括非索引属性和整个原型链。例如,
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.execreturns an array with additional properties, andfor-inwill iterate over them. Some libraries or even your own code may add additional methods toArray.prototype(either as polyfill or as custom methods), and if not done properly, they may be iterated over as well. -
它会跳过数组中的空位。虽然稀疏数组很少见,也不建议使用,但它们仍然是可行的,你的代码应该能够处理它们。
¥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.
-
“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-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.
¥Examples
¥Invalid
for (const i in array) { console.log(i, array[i]);}code-block.js:1:1 lint/nursery/noForIn ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
ℹ Unexpected for-in loop.
> 1 │ for (const i in array) {
│ ^^^^^^^^^^^^^^^^^^^^^^^^
> 2 │ console.log(i, array[i]);
> 3 │ }
│ ^
4 │
ℹ For-in loops are confusing and easy to misuse. You likely want to use a regular loop, for-of loop or forEach instead.
¥Valid
for (const value of array) { console.log(value);}for (let i = 0; i < array.length; i += 1) { console.log(i, array[i]);}array.forEach((value, i) => { console.log(i, value);});for (const [i, value] of array.entries()) { console.log(i, value);}¥Related links
Biome v2.1 中文网 - 粤ICP备13048890号