我的问题是分割一个包含逻辑运算的字符串。 例如,这是我的示例字符串:
var rule = "device2.temperature > 20 || device2.humidity>68 && device3.temperature >10"
我需要以一种可以轻松操作逻辑的方式解析该字符串,但我不确定哪种方法更好。
PS:请记住,这些规则字符串可以有 10 个或更多不同的条件组合,例如 4 个 AND 和 6 个 OR。
最佳答案
假设没有括号,我可能会使用这样的代码(JavaScript 代码):
function f(v,op,w){
var ops = {
'>': function(a,b){ return a > b; },
'<': function(a,b){ return a < b; },
'||': function(a,b){ return a || b; },
'&&': function(a,b){ return a && b; },
'==': function(a,b){ return a == b;}
}
if (ops[op]){
return ops[op](v,w);
} else alert('Could not recognize the operator, "' + op + '".');
}
现在,如果您可以设法获取表达式列表,则可以连续评估它们:
var exps = [[6,'>',7],'||',[12,'<',22], '&&', [5,'==',5]];
var i = 0,
result = typeof exps[i] == 'object' ? f(exps[i][0],exps[i][1],exps[i][2]) : exps[i];
i++;
while (exps[i] !== undefined){
var op = exps[i++],
b = typeof exps[i] == 'object' ? f(exps[i][0],exps[i][1],exps[i][2]) : exps[i];
result = f(result,op,b);
i++;
}
console.log(result);
关于javascript - javascript中基于AND OR逻辑分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36607204/