![](/img/trans.png)
[英]Why is my function using lodash _.forEach returning the same value?
[英]Javascript function using lodash forEach returning undefined
我正在編寫一個ReactJS應用程序,並且在filterSelected
函數中有一個for循環,該函數filterSelected
了區域名稱的數組(例如["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);
}
...
}
更新資料
我讀了你想做錯的事。 您需要執行以下操作:
country.countryName === region
查找regionCode 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
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.