如果profile.team_member_designations是一个数组,则运行以下代码。我想添加一个条件来过滤或检查profile_member_designations是否是一个数组,因为如果它是一个字符串,我不希望代码运行。基本上,就在map函数之前,我想过滤掉数组只运行代码。我该怎么做?
JS
var getTeamDesignations = function(profile) {
//Designations for a single team member
var teamDesignations = [];
if (profile.team_members) {
teamDesignations = _.chain(profile.team_members)
.map(_.property('team_member_designations'))
.flatten()
.uniq()
.value();
}
return teamDesignations;
};
答案 0 :(得分:1)
如果我理解你的问题,你想要这样的东西。
var getTeamDesignations = function(profile) {
//Designations for a single team member
var teamDesignations = [];
if (profile.team_members) {
teamDesignations = _.chain(profile.team_members)
.filter(_.compose(_.isArray, _.property('team_member_designations')))
.map(_.property('team_member_designations'))
.flatten()
.uniq()
.value();
}
return teamDesignations;
};
答案 1 :(得分:0)
如果条件如下,则替换如下:
if (profile.team_members && (profile.team_members instanceof Array)){
答案 2 :(得分:0)
<强>解决方案强>
var getTeamDesignations = function(profile) {
//Designations for a single team member
var teamDesignations = [];
if (profile.team_members && Array.isArray(profile.team_members)) {
teamDesignations = _.chain(profile.team_members)
.map(_.property('team_member_designations'))
.flatten()
.uniq()
.value();
}
return teamDesignations;
};
当参数是数组时,Array.isArray返回true。它也很好browser support。