Javascript 变量作为表达式给出意外的标识符错误

标签 javascript lodash

我有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/

相关文章:

php - Twitter REST API,更新状态?

javascript - lodash debounce 在匿名函数中不起作用

javascript - 减少包含几乎相同对象的数组

javascript - Underscore.js findWhere 嵌套对象

javascript - knockout js的optionsText绑定(bind)中编码的HTML

javascript - HTML 属性中是否允许使用 HTML?

javascript - 如何使用 openpgp.js 加密字符串?

javascript - React 调用函数?

javascript - Lodash Debounce 不去抖动

javascript - Lodash 或 Javascript - 按名称分组,然后按相等的字符串分组