三层统计最小力度的四种方法

厨房(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 递归** |

核心思想:不管用什么方法,都是在做一件事------**统计所有厨房里所有锅里的所有食材总数**。

相关推荐
镜宇秋霖丶7 小时前
2026.5.6@霖宇博客制作中遇见的问题
前端·javascript·vue.js
计算机专业码农一枚7 小时前
微信小程序 uniapp+vue高校社团管理
vue.js·微信小程序·uni-app
吴声子夜歌8 小时前
Vue3——TypeScript基础
javascript·typescript
小李子呢02118 小时前
前端八股Vue---Vue-router路由管理器
前端·javascript·vue.js
百锦再9 小时前
Auto.js变成基础知识学习
开发语言·javascript·学习·sqlite·kotlin·android studio·数据库开发
kyriewen1111 小时前
你等的Babel编译,够喝三杯咖啡了——用Rust重写的SWC,只需眨个眼
开发语言·前端·javascript·后端·性能优化·rust·前端框架
逍遥德12 小时前
AI时代,计算机专业大学生学习指南
java·javascript·人工智能·学习·ai编程
Rkgua13 小时前
JS中模拟函数重载的使用
javascript·jquery
竹林81813 小时前
用 wagmi v2 和 Next.js 14 硬扛 NFT 市场前端:从合约调用失败到批量上架,我踩了这些坑
javascript·next.js
Momo__13 小时前
Vue 3.6 Vapor Mode:跳过虚拟 DOM,性能极致优化
前端·vue.js