实际上,for-in循环并非遍历数组索引,而是遍历对象"自身拥有的与继承来的"所有属性。这正是它不可预测、容易出现非预期行为的原因所在。
你可能也写过类似这样的代码:
const fruits = ["apple", "banana", "cherry"];
for (let i in fruits) {
console.log(fruits[i]);
}
表面上看起来没有问题,能够正常打印水果名称。
那么为什么大家普遍不建议在数组上使用for...in呢?
因为它看似无害,实则暗藏隐患——某些情况下能用,但说不定哪天就会出问题。
for...in的真相
for...in本不是为数组设计的,它是用来遍历对象的——遍历可枚举的属性键:
const person = { name: "Alice", age: 25 };
for (let key in person) {
console.log(key); // name, age
}
用于对象:✅ 合理。用于数组:⚠️ 它依然遍历"属性键",而非"索引"。于是自定义属性、继承属性、非数字键都会进入循环。
隐藏炸弹一:额外的键
const fruits = ["apple", "banana", "cherry"];
fruits.color = "red";
for (let i in fruits) {
console.log(i);
}
输出:
0
1
2
color
