You need to enable JavaScript to run this app. 数组内对象增删:数组存在指定条目时修改对象键值,排查食材误删异常
优惠活动
大模型
产品
解决方案
定价
更多

数组内对象增删:数组存在指定条目时修改对象键值,排查食材误删异常

问题根源

核心逻辑写反

你取消勾选的分支里,判断条件完全颠倒:

// 你原有的逻辑
if (matched.name === eachIngredient.name && matched._id === eachIngredient._id) {
  // 直接删除食材
  this.groceryList.splice(index, 1);
} else {
  // 扣减数量
  matched.quantity = matched.quantity - eachIngredient.quantity;
}

你用name查找匹配食材,返回的matched必然满足name === eachIngredient.name;公共食材的_id在不同食谱里是统一的,所以这个if条件永远为真。只要取消勾选,找到匹配食材就直接删除,永远不会走扣减数量的分支,自然出现「仍有其他食谱包含该食材,却被从清单移除」的问题。

边界情况未处理

正确逻辑应该是:先扣减匹配食材的数量,只有扣减后数量≤0时,才从清单删除该食材。

空值未防护

如果查找不到匹配食材,matched会返回undefined,直接访问matched.name会抛出空指针错误。

数据引用风险

你勾选时直接把原食谱的食材对象push到groceryList,后续食谱的食材数据变动会意外篡改购物清单的内容。

修正后的实现
onCheckRecipe(e) {
  if (e.detail.checked) {
    // 直接定位目标食谱,不用遍历所有食谱
    const targetRecipe = this.loadedRecipes.find(recipe => recipe.name === e.detail.value);
    if (!targetRecipe) return;

    for (const eachIngredient of targetRecipe.ingredients) {
      const matchedIng = this.groceryList.find(item => item.name === eachIngredient.name);
      if (matchedIng) {
        matchedIng.quantity += eachIngredient.quantity;
      } else {
        // 拷贝食材对象,避免引用原数据
        this.groceryList.push({ ...eachIngredient });
      }
    }
  } else {
    const targetRecipe = this.loadedRecipes.find(recipe => recipe.name === e.detail.value);
    if (!targetRecipe) return;

    for (const eachIngredient of targetRecipe.ingredients) {
      const matchedIndex = this.groceryList.findIndex(item => item.name === eachIngredient.name);
      // 没找到对应食材直接跳过
      if (matchedIndex === -1) continue;

      const matchedIng = this.groceryList[matchedIndex];
      // 先扣减数量
      matchedIng.quantity -= eachIngredient.quantity;

      // 扣减后数量≤0才删除
      if (matchedIng.quantity <= 0) {
        this.groceryList.splice(matchedIndex, 1);
      }
    }
  }
}
可选优化

如果需要更稳定的购物清单同步逻辑,可以新增一个selectedRecipeIds数组维护已勾选的食谱ID,每次勾选/取消后清空groceryList,再遍历所有已勾选的食谱重新计算食材和数量,避免多次加减出现数值误差。

内容的提问来源于stack exchange,提问作者alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.25 06:24:00