這個小小的 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?? 沒錯,“color”也進循環了。一旦數組被加了額外屬性,for...in 就會照單全收。
隱藏炸彈二:繼承屬性(沉默 Bug)
Array.prototype.custom = "hi";
const arr = [1, 2, 3];
for (let i in arr) {
console.log(i);
}輸出:
0
1
2
custom你可能長期沒注意……直到某次線上突然炸鍋。
隱藏炸彈三:遍歷順序不保證
for...in 不保證順序。
當數組被當作對象對待時,順序也不再可靠:
const arr = [10, 20, 30];
arr[100] = 999;
for (let i in arr) {
console.log(i);
}你以為是 0, 1, 2, 100?不同引擎可能給你不同順序——不可預測。
正確替代方案 ????
需要遍歷數組請用下面這些:
1) for...of(遍歷值的首選)
const fruits = ["apple", "banana", "cherry"];
for (let fruit of fruits) {
console.log(fruit);
}→ 語義清晰、順序有保障、現代寫法。
2) 經典 for(需要索引或追求極致性能)
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}→ 大數組下仍然穩、快、可控。
3) forEach()(函數式風格)
fruits.forEach(fruit => console.log(fruit));→ 簡潔、易讀,適合簡單遍歷。
口決一條(貼在工位)

- ????
for...in→ 對象(遍歷鍵) - ????
for...of→ 數組(遍歷值) - ??♀? 別混用
當你在數組上寫下:
for (let i in arr)其實并不是“遍歷索引”,而是遍歷它“擁有的 + 繼承的”一切屬性。 這就是它不可預測、脆弱、偶發災難的根源。
下次看到有人這么寫,立刻攔住他!如果本文幫到你,點個贊、關注、留言,讓更多同學別踩這個坑。





























