【问题标题】:Javascript function using lodash forEach returning undefined使用 lodash forEach 的 Javascript 函数返回未定义
【发布时间】:2018-11-29 10:23:58
【问题描述】:

我正在编写一个 ReactJS 应用程序,并且我在函数 filterSelected 中有一个 for 循环,它通过区域名称数组(例如["Thailand", "Malaysia"])并应该返回它们相应区域代码的数组(例如。 ["TH", "MY"])。

在我的mapRegionToCode 函数中,它通过对象的对象进行此映射,并且控制台日志正确打印​​相应的区域代码,但是该函数返回undefined

任何想法为什么将不胜感激!

mapRegionToCode(region) { // region = "Thailand"
  _.forEach(_.values(this.props.regionsCodes), regionCode => {
    if(regionCode.country.countryName === region) {
      console.log(regionCode.country.countryCode); //"TH"
      return regionCode.country.countryCode;
    }
  });
}

filterSelected(filters) {
...
  for(let i = 0; i < regionsArray.length; i++){
    const regionCode = this.mapRegionToCode(regionName);
    console.log(regionCode); //undefined
    regionNames.push(regionCode);
  }
...
}

【问题讨论】:

  • 我想你的意思是_.map 不是forEach

标签: javascript reactjs for-loop return lodash


【解决方案1】:

更新

我读到你想做错了什么。您需要做的是:

  1. 使用country.countryName === region 查找区域代码
  2. 返回其country.countryCode

使用 lodash,您可以执行以下操作:

mapRegionToCode(region) {
  return _.find(_.values(this.props.regionsCodes),regionCode => regionCode.country.countryName === region).country.countryCode
}

原答案

您忘记在mapRegionToCode 函数中添加return

mapRegionToCode(region) { // region = "Thailand"
  return _.map(_.values(this.props.regionsCodes), regionCode => {
    if(regionCode.country.countryName === region) {
      console.log(regionCode.country.countryCode); //"TH"
      return regionCode.country.countryCode;
    }
  });
}

(另外,你需要使用_.map而不是_.forEach

【讨论】:

  • 这会导致 mapRegionToCode("Thailand") 返回一个大小为 243 的数组,而不是 "TH"
  • 这工作谢谢!仍然不确定为什么我的代码不起作用,但我得到了回报
  • 您在传递给 _.map 的函数中使用了 return。这意味着它为此函数返回,而不是 mapRegionToCode 函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-17
  • 2019-01-07
  • 1970-01-01
  • 2019-07-04
  • 2016-01-23
  • 2021-08-21
  • 1970-01-01
相关资源
最近更新 更多