useForOf
Esta página aún no está disponible en tu idioma.
Summary
Section titled “Summary”- Rule available since:
v1.5.0
- Diagnostic Category:
lint/style/useForOf
- This rule doesn’t have a fix.
- The default severity of this rule is information.
- Sources:
- Same as
@typescript-eslint/prefer-for-of
- Same as
unicorn/no-for-loop
- Same as
Description
Section titled “Description”Prefer using for...of
loops over standard for
loops where possible.
This rule recommends using a for...of
loop in place of a for
loop
when the loop index is solely used to read from the iterated array.
Exceptions for Index Usage
Section titled “Exceptions for Index Usage”When the loop index is declared within the outer scope or used anywhere within the loop body,
it is acceptable to use a for
loop.
(Array.entries()
can be used to a similar effect.)
Examples
Section titled “Examples”Invalid
Section titled “Invalid”for (let i = 0; i < array.length; i++) { console.log(array[i]);}
code-block.js:1:1 lint/style/useForOf ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
ℹ Use for-of loop instead of a for loop.
> 1 │ for (let i = 0; i < array.length; i++) {
│ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
> 2 │ console.log(array[i]);
> 3 │ }
│ ^
4 │
for (let item of array) { console.log(item); }
for (let i = 0; i < array.length; i++) { // `i` is used, so for loop is OK console.log(i, array[i]); }
for (let i = 0, j = 0; i < array.length; i++) { console.log(i, array[i]); }
let i = 0;for (; i < array.length; i++) { console.log(array[i]); }
How to configure
Section titled “How to configure”{ "linter": { "rules": { "style": { "useForOf": "error" } } }}