Urara-Blog/node_modules/.pnpm-store/v3/files/d7/e8b9990a963eb0de77cec72575cd483d348619d40722b9f51d7abe21e988114598c4148288c26a2269cfe35acecf168b845ca8ec536b72e0a54ceb75cee1d9
2022-08-14 01:14:53 +08:00

60 lines
1.3 KiB
Text

---
description: 'Enforce the use of `for-of` loop over the standard `for` loop where possible.'
---
> 🛑 This file is source code, not the primary documentation location! 🛑
>
> See **https://typescript-eslint.io/rules/prefer-for-of** for documentation.
This rule recommends a for-of loop when the loop index is only used to read from an array that is being iterated.
## Rule Details
For cases where the index is only used to read from the array being iterated, a for-of loop is easier to read and write.
Examples of code for this rule:
<!--tabs-->
### ❌ Incorrect
```js
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
```
### ✅ Correct
```js
for (const x of arr) {
console.log(x);
}
for (let i = 0; i < arr.length; i++) {
// i is used to write to arr, so for-of could not be used.
arr[i] = 0;
}
for (let i = 0; i < arr.length; i++) {
// i is used independent of arr, so for-of could not be used.
console.log(i, arr[i]);
}
```
## Options
```jsonc
// .eslintrc.json
{
"rules": {
"@typescript-eslint/prefer-for-of": "warn"
}
}
```
This rule is not configurable.
## When Not To Use It
If you transpile for browsers that do not support for-of loops, you may wish to use traditional for loops that produce more compact code.