获取未定义而不是函数的返回值

时间:2021-04-01 15:43:00

标签: javascript jquery

我有两个对象的简单数组,我需要在其中获取 1 个月的产品价格。

数组可以有 2 或 3 个项目,所以我正在检查它是 2 还是 3。然后我将对象存储在它们自己的变量中,并使用这些变量的参数值调用函数 getOneMonthPrice。< /p>

函数 getOneMOnthPrice 遍历产品并检查月属性是否为 01 month 的值,如果是,则返回价格。

但现在我只是未定义,而如果我在函数中使用 console.log,我可以看到控制台中显示的值。

这里出了什么问题?

请注意,我实际上已经从我正在处理的实际项目中删除了大部分代码。这只是最短的版本。如果可以,请给我一个基于这种格式的解决方案。

这是片段:

const arr = [{
    "name": "Boom Boom Ltd.",
    "products": [{
        "price": "3.33",
        "months": "24 months"
      },
      {
        "price": "10.95",
        "months": "01 month"
      }
    ]
  },
  {
    "name": "Bam Bam Ltd.",
    "products": [{
        "price": "5.93",
        "months": "24 months"
      },
      {
        "price": "12.95",
        "months": "01 month"
      }
    ]
  }
];


function getOneMonthPrice(company) {
  company.products.forEach(item => {
    if (item.months === "01 month") {
      return item.price;
    }
  });
};


if (arr.length === 2) {
  const company1 = arr[0];
  const company2 = arr[1];

  console.log(getOneMonthPrice(company1));
}

1 个答案:

答案 0 :(得分:0)

forEach 回调函数返回不会从包含函数返回。

您可以使用 forEach 来查找符合您条件的数组元素,而不是 find(),然后从中返回价格。

function getOneMonthPrice(company) {
  let product = company.products.find(item => item.months === "01 month");
  return product && product.price;
}
相关问题