parsing+从JSON对象评估expression式而不使用Eval()?
我正在构build一个节点应用程序,用户(理想情况下)能够使用一系列JSON对象为地理数据定义样式:
{ "style": { "test": "year", "condition": "<= 1954 AND >= 1936", "color": "red" } }
在上面的情况下,我喜欢评估这种风格
if (year <= 1954 && year >= 1936){ object.color = red; }
有没有一种简单的方法来parsing+评估这样的expression式/从这样的对象build立它们? 我特别感兴趣的是让人们用<=,> =,||,&&等构build复杂的expression式。
如果可能,我想避免使用eval()。
如果你不想使用eval,你将不得不编写自己的小parsing器,并创build一个像这样的定义语言:
"condition": ["and", ["<=", 1954], [">=", 1936]],
这是您可以考虑的部分实现:
function do_and(args, value) { for (var i = 0; i < args.length; ++i) { if (!evaluate(args[i], value)) { return false; } } return true; } function evaluate(condition, value) { switch (condition[0]) { case "and": return do_and(condition.slice(1), value); case "<=": return value <= condition[1]; case ">=": return value >= condition[1]; } }
这是你将如何使用它:
var style = { "test": "year", "condition": ["and", ["<=", 1954], [">=", 1936]], "color": "red" }, context = { "year": 1940 }; if (evaluate(style.condition, context[style.test])) { console.log(style.color); // "red" }
演示
就像是
var obj = JSON.parse(str); switch (obj.style.operator){ case '=': if (window[obj.style.condition] === obj.style){//assuming that the conditions are global object.color = obj.style; } break; ... }