Skip to content

useForOf

¥Summary

¥How to configure

biome.json
{
"linter": {
"rules": {
"style": {
"useForOf": "error"
}
}
}
}

¥Description

尽可能优先使用 for...of 循环而不是标准的 for 循环。

¥Prefer using for...of loops over standard for loops where possible.

当循环索引仅用于从迭代数组中读取数据时,此规则建议使用 for...of 循环代替 for 循环。

¥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

当循环索引在外部作用域内声明或在循环体中的任何位置使用时,可以使用 for 循环。(Array.entries() 可以用于类似的效果。)

¥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

¥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 │

¥Valid

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]);
}

¥Related links