noForIn
Este conteúdo não está disponível em sua língua ainda.
Summary
Section titled “Summary”- Diagnostic Category:
lint/nursery/noForIn - This rule doesn’t have a fix.
- The default severity of this rule is information.
- Sources:
- Inspired from
@typescript-eslint/no-for-in-array
- Inspired from
How to configure
Section titled “How to configure”{ "linter": { "rules": { "nursery": { "noForIn": "error" } } }}Description
Section titled “Description”Disallow iterating using a for-in loop.
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:
- 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.
- The “index” is returned as a string, not a number. This can be caught by TypeScript, but can still lead to subtle bugs.
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
Section titled “Examples”Invalid
Section titled “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.
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
Section titled “Related links”Copyright (c) 2023-present Biome Developers and Contributors.