我有java脚本代码用于根据某个值过滤数组。
在此,我将一行代码 _(obj.boardingPoints).map('location').intersection(json[0]).value().length > 0
分配给名为st
的变量
var st='_(obj.boardingPoints).map('location').intersection("'+json[0]+'").value().length > 0'
并替换了过滤数组代码中的变量st
var tresult = _.filter(result, function(obj) {
return
st||_(obj.droppingPoints).map('location').intersection(dpLocations).value().length > 0
|| _.includes(busTypes, obj.busType)
|| _.includes(operatorNames, obj.operatorName);
});
但是这行会抛出意外的标识符错误
var st='_(obj.boardingPoints).map('location').intersection("'+json[0]+'").value().length > 0
'
最佳答案
好的,根据您在评论中的回复。我认为我有足够的信息来编写答案,假设 json[i] 是一个字符串数组:
var tresult = _.filter(result, function(obj) {
return _(obj.boardingPoints).map('location').intersection(json[i]).value().length > 0
|| _(obj.droppingPoints).map('location').intersection(dpLocations).value().length > 0
|| _.includes(busTypes, obj.busType)
|| _.includes(operatorNames, obj.operatorName);
});
您可以将表达式分配给变量,但我认为在这种情况下没有任何真正的好处。但是,如果您确实坚持将表达式分配给变量,请将其保留为表达式,将其转换为字符串是行不通的。这是将第一个表达式分配给变量的代码:
var tresult = _.filter(result, function(obj) {
var st = _(obj.boardingPoints).map('location').intersection(json[i]).value().length > 0;
return
st || _(obj.droppingPoints).map('location').intersection(dpLocations).value().length > 0
|| _.includes(busTypes, obj.busType)
|| _.includes(operatorNames, obj.operatorName);
});
关于Javascript 变量作为表达式给出意外的标识符错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35629940/