2016-08-24 72 views
1
返回undefined

我不希望这个地图我怎么能做到这一点返回undefined?上Array.map

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); 
+0

它看起来像这个问题可能是MSP语句中的条件,但你真的应该得到一个小提琴来证明这个问题。 – Sudsy

+0

哇它返回undefind当res.compareSelected = false..i不认为它需要更多的信息 – FreakProgrammer

回答

0

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

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

TL; DR

使用Array.filter方法之后Array.map除去不确定的因素在新阵列中。


扩大对@ Bloomca的回答是:

As stated in the documentation provided here

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

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

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

[ undefined, 2, 3 ]

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

这就是为什么上面提供的答案将不再导致新阵列内undefined元件。如果条件res.compareSelected == true是不是真的到其他块内的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.

相关问题