2011-09-09 39 views
3

例如:如何从字符串调用并执行一个操作符?

var s = '3+3'; 
s.replace(/([\d.]+)([\+\-)([^,]*)/g, 
     function(all, n1, operator, n2) { 
       r = new Number(n1) ??? new Number(n2); 
       return r; 
     } 
); 

注:不使用eval()

+0

貌似其中'EVAL为数不多的案例之一()'将方便。 – alex

+0

'new Function()'是否也禁用? – alex

+0

为什么不出于好奇使用'eval()'? –

回答

5

Are Variable Operators Possible?

不可能的开箱即用,但他给出了一个很好的实现来做到这一点,如下所示。编号delnan

var operators = { 
    '+': function(a, b) { return a + b }, 
    '<': function(a, b) { return a < b }, 
    // ... 
}; 

var op = '+'; 
alert(operators[op](10, 20)); 

因此,对于你实现

r = operators[operator](new Number(n1), new Number(n2)); 
+1

+1用于使用该对象查找运算符函数而不是if/else或switch/case。 – jfriend00

1

你的正则表达式是有点破。

/([\d.]+)([\+\-)([^,]*)/g 

也许应该

/([\d.]+)([+-])([\d+]+)/g 

,那么你可以对操作进行切换:

function (_, a, op, b) { 
    switch (op) { 
    case '+': return a - -b; 
    case '-': return a - b; 
    } 
} 
0
s.replace(/(\d+)\s*([+-])\s*(\d+)/g, function(all, s1, op, s2) { 
    var n1 = Number(s1), n2 = Number(s2); 
    return (op=='+') ? (n1+n2) : (n1-n2); 
}); 
相关问题