2013-05-01 123 views
2

我试图通过评估在表达一个特定函数调用来模拟在JavaScript懒评价一个特定的功能,同时使其他功能原样。是否可以在不评估其他函数的情况下评估表达式中的一个函数(以使表达式中的所有其他函数调用保持原样)?评估在JavaScript语句

这里是我想要实现的功能:

function evaluateSpecificFunction(theExpression, functionsToEvaluate){ 
    //Evaluate one specific function in the expression, and return the new expression, with one specific function being evaluated 
} 

例如:

evaluateSpecificFunction("addTwoNumbers(1, 2) + getGreatestPrimeFactor(10)", addTwoNumbers); 
//This should return "3 + getGreatestPrimeFactor(10)", since only one of the functions is being evaluated 

evaluateSpecificFunction("addTwoNumbers(1, 2) + getGreatestPrimeFactor(10)", getGreatestPrimeFactor); 
//This should return "addTwoNumbers(1, 2) + 5"; 
+2

你必须做解析,在这里,或使用替代品。 – 2013-05-01 18:04:51

+0

可以解析参数1串 – 2013-05-01 18:05:04

+0

@MikeHometchko哪个字符串是“参数1字符串”? – 2013-05-01 18:05:25

回答

3

你可以做的是replace和正则表达式玩:

function getGreatestPrimeFactor(n) { 
    return n*2; 
} 

function transform(s, f) { 
    return s.replace(new RegExp(f+"\\(([^\\)]*)\\)", "g"), function(m, args) { 
    return window[f].apply(null, args.split(',').map(function(v){ 
     return parseFloat(v) 
    })); 
    }); 
} 


var result = transform(
    "addTwoNumbers(1, 2) + getGreatestPrimeFactor(10)", 
    "getGreatestPrimeFactor" 
); 

这个例子假定你只处理数字参数。

Demonstration (open the console)

当然,这主要是代码演示了主意,你应该,例如,存储在专用对象的功能,而不是全球范围内(window)。

编辑:新版本可以处理一个以上的替代品。

+0

为什么不使用'return eval(m);'?这里可能是适当的。而且顺便说一句,你的正则表达式涉及严重与:-) – Bergi 2013-05-01 18:20:34

+0

@Bergi嵌套表达式:因为'窗口[F]'可能比'eval'更快。 – 2013-05-01 18:21:33

+0

@Bergi处理嵌套表达式意味着解析表达式,而不仅仅是使用正则表达式。当我可以避免'eval',我避免它... – 2013-05-01 18:23:45