Skip to content
← Back to rules

typescript/no-for-in-array 正确性

This rule is turned on by default when type-aware linting is enabled.
💭 This rule requires type information.

它的作用

此规则禁止使用 for-in 循环遍历数组。

为什么这是错误的?

for-in 循环会遍历对象的可枚举属性,这包括数组索引,但也包括添加到数组原型或数组实例上的任何可枚举属性。在遍历数组时,这种情况几乎从来不是你想要的行为。

示例

以下为 错误 的代码示例:

ts
const arr = [1, 2, 3];

for (const i in arr) {
  console.log(arr[i]);
}

for (const i in arr) {
  console.log(i, arr[i]);
}

以下为 正确 的代码示例:

ts
const arr = [1, 2, 3];

// 使用 for-of 遍历数组值
for (const value of arr) {
  console.log(value);
}

// 使用常规 for 循环配合索引
for (let i = 0; i < arr.length; i++) {
  console.log(i, arr[i]);
}

// 使用 forEach
arr.forEach((value, index) => {
  console.log(index, value);
});

// for-in 对于对象是合适的
const obj = { a: 1, b: 2 };
for (const key in obj) {
  console.log(key, obj[key]);
}

如何使用

要通过配置文件或 CLI 启用 此规则,可以使用:

json
{
  "rules": {
    "typescript/no-for-in-array": "error"
  }
}
bash
oxlint --type-aware --deny typescript/no-for-in-array

参考资料