厨房(Kitchen)
└── 锅(Pot)
└── 食材(Ingredient)
三种统计"总食材数"的方法
1. 用 flatMap 扁平化后求和 ⭐推荐
```typescript
const totalIngredientCount = computed(() => {
// 从所有厨房中,拿到所有锅,再拿到所有食材,最后统计
const allIngredients = kitchens.value.flatMap(kitchen =>
kitchen.pots.flatMap(pot => pot.ingredients ?? [])
)
return allIngredients.length
})
```
**优点**:逻辑清晰------先拿到所有食材,再数数有多少。
**缺点**:会创建多个中间数组,如果厨房很多、锅很多,性能稍差(但通常厨房场景数据量不大)。
2. 递归函数(更灵活,但略"重")
```typescript
const sumIngredients = (items: any[]) => {
return items.reduce((sum, item) => {
if (item.ingredients) return sum + item.ingredients.length // 是锅,直接加食材数
if (item.pots) return sum + sumIngredients(item.pots) // 是厨房,递归统计锅里的
return sum
}, 0)
}
const totalIngredientCount = computed(() => sumIngredients(kitchens.value))
```
**优点**:扩展性好,不怕层级变化(比如以后锅下面再加一层"篮子")。
**缺点**:需要类型判断,不够直接,小场景用大炮。
3. 显式两层循环(性能最优,可读性中等)
```typescript
const totalIngredientCount = computed(() => {
let count = 0
for (const kitchen of kitchens.value) { // 遍历每个厨房
for (const pot of kitchen.pots) { // 遍历厨房的每口锅
count += pot.ingredients?.length ?? 0 // 累加锅里的食材数
}
}
return count
})
```
**优点**:性能最好,逻辑直观(就是两层循环数数:厨房→锅→食材)。
**缺点**:代码行数稍多,但比 reduce 嵌套容易读懂。
用reduce
```
const totalCount = computed(() =>
kitchen.value.reduce((count,kitchent) =>
count + kitchen.Pot.reduce((PotCount, Pot) => {
return PotCount + Pot.Ingredient.reduce((IngredientCount, Ingredient) => IngredientCount+ (Ingredient.creativeGroups?.length || 0), 0)
}, 0), 0)
)
```
🎯 总结
| 场景 | 推荐方案 |
|------|---------|
| 代码简洁优先 | **方案1 flatMap** |
| 数据量大、性能敏感 | **方案3 显式循环** |
| 层级可能动态变化 | **方案2 递归** |
核心思想:不管用什么方法,都是在做一件事------**统计所有厨房里所有锅里的所有食材总数**。