0

我正在用 javascript 创建一个程序,但我不知道如何实现以下目标;我的程序将诸如“+”、“-”之类的参数和其他数学运算符作为我想转换为实际运算符的字符串。例如(伪代码):

function calc(a,b,c, op1,op2){

  output=(a op1 b op2  c)
 }

计算(2,3,4,"+","-")

输出现在应该是 = 2+3-4。

但是,我事先不知道我将拥有多少运营商以及数量。换句话说,我的目标是替换 1,"+",2, "-",4,"+","(",5,"+",6,")"........ .等等 1+2-4+(5+6).....

我怎样才能以一种很好的方式实现这一点?

4

3 回答 3

4

好吧,你可以使用eval,但你可以这样做:

   var funcs = {
       '+': function(a,b){ return a+b },
       '-': function(a,b){ return a-b }
   };
   function calc(a,b,c, op1,op2){
      return funcs[op2](funcs[op1](a, b), c);
   }

funcs您可以使用其他运营商轻松扩展地图。

于 2013-06-18T19:34:16.063 回答
1

I really would suggest using eval for this particular case:

eval("var res = " + 1 + "+" + 2 + "-" + 4 + "+" + "(" + 5 + "+" + 6 + ")");
console.log(res); //10

I know, I know, everone says you should avoid eval where possible. And they are right. eval has great power and you should only use it with great responsibility, in particular when you evaluate something, that was entered by the end user. But if you are careful, you can use eval and be fine.

于 2013-06-18T19:47:22.570 回答
1

这已经完成得非常快,但应该可以解决问题(此处为 JSFiddle):

function executeMath() {
    if (arguments.length % 2 === 0) return null;
    var initialLength = arguments.length,
        numberIndex = (initialLength + 1)/2,
        numbers = Array.prototype.splice.call(arguments, 0, numberIndex),
        operands = Array.prototype.splice.call(arguments, 0),
        joiner = new Array(arguments.length);
    for (var i = 0; i < numbers.length; i++) {
        joiner[i*2] = numbers[i];
    }
    for (var i = 0; i < operands.length; i++) {
        joiner[1+(i*2)] = operands[i];
    }
    var command = ("return (" + joiner.join('') + ");"),
        execute = new Function(command);
    console.log(command);
    return execute();
}
console.log(executeMath(2, 3, 4, 5, "/", "+", "%"));
于 2013-06-18T20:10:51.553 回答