【问题标题】:Getting undefined instead of the return value of a function [duplicate]获取未定义而不是函数的返回值[重复]
【发布时间】:2021-04-01 15:43:00
【问题描述】:

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

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

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

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

这里出了什么问题?

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

这是sn-p:

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));
}

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

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

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

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

    【讨论】:

    • 我会这样做,以防找不到产品。如果我只返回product.price,如果product == null 会出错
    • @A.Amit 您不能短路或停止 forEach,因此对于大多数(如果不是全部)场景,使用 foreach 执行此操作没有任何价值。
    • 大致相当于if (product) return product.price;
    • 您应该选择我的,因为它会在找到月份后立即停止搜索。 forEach 将继续处理数组的其余部分。
    • @A.Amit 选择 Barmar's。除非你打破你的 forEach,否则他是更好的答案。
    猜你喜欢
    • 2019-05-17
    • 1970-01-01
    • 2020-01-28
    • 2018-07-03
    • 2021-09-11
    • 2016-07-25
    • 2018-05-08
    • 2015-12-26
    • 2017-02-07
    相关资源
    最近更新 更多