typescript/no-for-in-array 正确性
它的作用
此规则禁止使用 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]);
}如何使用
To enable this rule using the config file or in the CLI, you can use:
json
{
"options": {
"typeAware": true
},
"rules": {
"typescript/no-for-in-array": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
options: { typeAware: true },
rules: {
"typescript/no-for-in-array": "error",
},
});bash
oxlint --type-aware --deny typescript/no-for-in-array版本
此规则在 v1.12.0 中添加。
