var s = '3+3';
s.replace(/([\d.]+)([\+\-)([^,]*)/g,
function(all, n1, operator, n2) {
r = new Number(n1) ??? new Number(n2);
return r;
}
);
注:不使用eval()
var s = '3+3';
s.replace(/([\d.]+)([\+\-)([^,]*)/g,
function(all, n1, operator, n2) {
r = new Number(n1) ??? new Number(n2);
return r;
}
);
注:不使用eval()
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用于使用该对象查找运算符函数而不是if/else或switch/case。 – jfriend00
你的正则表达式是有点破。
/([\d.]+)([\+\-)([^,]*)/g
也许应该
/([\d.]+)([+-])([\d+]+)/g
,那么你可以对操作进行切换:
function (_, a, op, b) {
switch (op) {
case '+': return a - -b;
case '-': return a - b;
}
}
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);
});
貌似其中'EVAL为数不多的案例之一()'将方便。 – alex
'new Function()'是否也禁用? – alex
为什么不出于好奇使用'eval()'? –