【发布时间】:2016-03-12 05:53:21
【问题描述】:
我正在尝试使用lodash.js 实现过滤功能,以根据某些参数显示总线列表。
这里有 4 个参数用于过滤 boardingPoint、droppingPoint、busType 和 operatorName,它将被填充到 4 个下拉菜单中。
工作流程
当用户选择一个登机点时,结果应该只包含带有选定登机点的巴士列表,
如果他选择了上车点和下车点,结果应该只包含选择了上车点和下车点等的巴士列表。
这是我的过滤功能
function search_buses(bpLocations,dpLocations,busTypes,operatorNames){
//filter function
tresult = _.filter(result, function(obj) {
return _(obj.boardingPoints).map('location').intersection(bpLocations).value().length > 0
&&_(obj.droppingPoints).map('location').intersection(dpLocations).value().length > 0
&& _.includes(busTypes, obj.busType)
&& _.includes(operatorNames, obj.operatorName);
});
//return result array
return tresult;
}
但问题是,如果用户只选择了两个项目,即登机点和下机点,而其他项目为空,则上述过滤条件失败,因为它将评估四个条件。 只有当所有 4 个参数都具有任何值时,上述方法才有效。
那么我该如何修改上面的表达式,它应该只包含用于过滤的选定参数
例如:如果用户选择登机点和下机点(即bpLocations,dpLocations),则只有表达式应该是这个
tresult = _.filter(result, function(obj) {
return _(obj.boardingPoints).map('location').intersection(bpLocations).value().length > 0
&&_(obj.droppingPoints).map('location').intersection(dpLocations).value().length > 0
});
如果只选择 busType 它应该是
tresult = _.filter(result, function(obj) {
return _.includes(busTypes, obj.busType)
});
更新
我只是根据每个变量是否为空来连接表达式字符串
//expression string
var finalvar;
tresult = _.filter(result, function(obj) {
if(bpLocations!=''){
finalvar+=_(obj.boardingPoints).map('location').intersection(bpLocations).value().length > 0;
}
if(dpLocations!=''){
finalvar+=&&+_(obj.droppingPoints).map('location').intersection(dpLocations).value().length > 0;
}
if(busTypes!=''){
finalvar+=&&+ _.includes(busTypes, obj.busType);
}
if(operatorNames!=''){
finalvar+=&&+ _.includes(operatorNames, obj.operatorName);
}
return finalvar;
});
但它会返回这个错误Uncaught SyntaxError: Unexpected token &&
【问题讨论】:
标签: javascript jquery html lodash