微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

不工作的 javascript 代码 - 某种缓存问题?

如何解决不工作的 javascript 代码 - 某种缓存问题?

  Array.forEach((element) => {
    recipes.forEach((curr,index) => {
      found = true;
      item = element;
      if (!curr.ingredients.includes(element)) found = false;
      if (index + 1 === recipes.length && found === false) {
        console.log(element,false);
      } else if (index + 1 === recipes.length && found === true) {
        console.log(element,true);
        foundItem = element;
      }
    });
  });
  return foundItem;

大家好...我正在尝试调试这样的代码...正在发生的事情是,如下图所示,我的代码正在返回“açúcar”、“calabresa”和“ cerveja”。 Image where you can see the output from my console

然而,这不是我的意思,因为我正在遍历一个 JSON 列表,该列表恰好包含几种不同食谱的成分...... 如下

  "recipes": [
    {
      "id": "00832498-3acc-4bde-9d89-77eacef26680","title": "Excelente pudim de milho","ingredients": [
        "abóbora","aveia","azeite","açúcar","cerveja","frango","milho","morango","vinho"
      ],"price": 78.53
    },{
      "id": "008b345d-8f7c-427d-988b-4f238b8315f2","title": "Excelente bolo de azeite","price": 82.55
    },{
      "id": "00d14194-f223-447e-86a0-b535c451d53f","title": "Exuberante coxinha de vinho","calabresa","chuchu","uva",

我想要的是 açucar,因为它是所有食谱中唯一存在的成分... 至于我,这里似乎存在某种与缓存相关的问题

解决方法

也许你可以把你的代码改成这样:

Array.forEach((element) => {
  const isIncluded = recipes.every(recipe => recipe.ingredients.includes(element));
  if (isIncluded) {
    // Do something with the ingredient or the element.
  }
});
return foundItem;

every 方法检查每个食谱是否包含您传递给它的成分。

,

如果你可以访问 lodash,你可以让它变得非常干净

import { intersection } from 'lodash'

getCommonIngredients = (recipes) => {
  const ingredients = recipes.map(recipe => recipe.ingredients)
  return intersection(...ingredients)
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。