【问题标题】:Return undefined on Array.map [duplicate]在 Array.map 上返回未定义 [重复]
【发布时间】:2016-08-24 09:54:54
【问题描述】:

我不希望这张地图返回 undefined 我该怎么做?

var onCompareSelectedClick = function () {
            var talentProfileInfoForAppliedResources = appliedResourcesEntries.map(function(res) {
                console.log(res);
                if(res.compareSelected == true) {
                    return data.getTalentProfileInfo(res.RES.RES_ID);
                }
            });
            console.log(talentProfileInfoForAppliedResources);
            this.openCompareTPDlg(talentProfileInfoForAppliedResources);
        }.bind(this);

【问题讨论】:

  • 看起来问题可能出在 msp 语句中的条件问题上,但您真的应该得到一个小提琴来证明这个问题。
  • 哇,当 res.compareSelected = false 时它返回 undefind ..我认为不需要更多信息

标签: javascript arrays reactjs


【解决方案1】:

只需在返回所需值的map 方法中添加else 语句,例如:

if(res.compareSelected == true) {
   return data.getTalentProfileInfo(res.RES.RES_ID);
} else {
   return 'default_value';
}

【讨论】:

    【解决方案2】:

    TL;DR

    在 Array.map 之后使用 Array.filter 方法来移除新数组中未定义的元素。


    扩展@Bloomca 的回答:

    As stated in the documentation provided here.

    map() 方法创建一个新数组,其结果是对该数组中的每个元素调用提供的函数。

    因此,您的新数组包含未定义元素的原因是因为您没有在函数内显式调用 return 对使用提供的函数调用的某些元素。在 Javascript 中,不显式调用 return 仍然会返回 undefined

    例如,在下面的方法中 newArray 将被设置为记录的结果:

    [ undefined, 2, 3 ]

    newArray = [1,2,3].map(function(elem) { if (elem > 1) return elem })
    console.log(newArray)
    

    这就是为什么上面提供的答案将不再导致新数组中的undefined 元素。如果条件 res.compareSelected == true 不符合 else 块中的 return 语句,则条件将解析(注意,您可以简单地在此处删除 true 并简单地放置 res.compareSelected,这将是更好的做法)。

    根据您的问题,您可能会发现使用Array.filter 方法返回没有未定义值的Array。并且仅使用您调用函数data.getTalentProfileInfo(res.RES.RES_ID) 的值。

    您可以通过以下方式执行此操作:

    var onCompareSelectedClick = function () {
        var arr = appliedResourcesEntries.map(function(res) {
            if(res.compareSelected == true) {
                return data.getTalentProfileInfo(res.RES.RES_ID);
            }
        });
        var talentProfileInfoForAppliedResources = arr.filter(function(elem) {
            return elem;
        });
    console.log(talentProfileInfoForAppliedResources);
    this.openCompareTPDlg(talentProfileInfoForAppliedResources);
    }.bind(this);
    

    You can read about the Array.filter method here.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-25
      • 2020-09-05
      • 2018-04-13
      • 2019-05-30
      • 2018-10-24
      • 2020-06-16
      • 2019-10-01
      • 2018-03-25
      相关资源
      最近更新 更多