Evaluating a string as a mathematical expression i

2018-12-31 12:04发布

How do I parse and evaluate a mathematical expression in a string (e.g. '1+1') without invoking eval(string) to yield its numerical value?

With that example, I want the function to accept '1+1' and return 2.

14条回答
残风、尘缘若梦
2楼-- · 2018-12-31 12:31

You can use the JavaScript Expression Evaluator library, which allows you to do stuff like:

Parser.evaluate("2 ^ x", { x: 3 });

Or mathjs, which allows stuff like:

math.eval('sin(45 deg) ^ 2');

I ended up choosing mathjs for one of my projects.

查看更多
明月照影归
3楼-- · 2018-12-31 12:33

Here is an algorithmic solution similar to jMichael's that loops through the expression character by character and progressively tracks left/operator/right. The function accumulates the result after each turn it finds an operator character. This version only supports '+' and '-' operators but is written to be extended with other operators. Note: we set 'currOp' to '+' before looping because we assume the expression starts with a positive float. In fact, overall I'm making the assumption that input is similar to what would come from a calculator.

function calculate(exp) {
  const opMap = {
    '+': (a, b) => { return parseFloat(a) + parseFloat(b) },
    '-': (a, b) => { return parseFloat(a) - parseFloat(b) },
  };
  const opList = Object.keys(opMap);

  let acc = 0;
  let next = '';
  let currOp = '+';

  for (let char of exp) {
    if (opList.includes(char)) {
      acc = opMap[currOp](acc, next);
      currOp = char;
      next = '';
    } else {
      next += char;
    } 
  }

  return currOp === '+' ? acc + parseFloat(next) : acc - parseFloat(next);
}
查看更多
美炸的是我
4楼-- · 2018-12-31 12:40

// You can do + or - easily:

function addbits(s){
    var total= 0, s= s.match(/[+\-]*(\.\d+|\d+(\.\d+)?)/g) || [];
    while(s.length){
        total+= parseFloat(s.shift());
    }
    return total;
}

var string='1+23+4+5-30';
addbits(string)

More complicated math makes eval more attractive- and certainly simpler to write.

查看更多
旧人旧事旧时光
5楼-- · 2018-12-31 12:40

I've eventually gone for this solution, which works for summing positive and negative integers (and with a little modification to the regex will work for decimals too):

function sum(string) {
  return (string.match(/^(-?\d+)(\+-?\d+)*$/)) ? string.split('+').stringSum() : NaN;
}   

Array.prototype.stringSum = function() {
    var sum = 0;
    for(var k=0, kl=this.length;k<kl;k++)
    {
        sum += +this[k];
    }
    return sum;
}

I'm not sure if it's faster than eval(), but as I have to carry out the operation lots of times I'm far more comfortable runing this script than creating loads of instances of the javascript compiler

查看更多
若你有天会懂
6楼-- · 2018-12-31 12:43

Somebody has to parse that string. If it's not the interpreter (via eval) then it'll need to be you, writing a parsing routine to extract numbers, operators, and anything else you want to support in a mathematical expression.

So, no, there isn't any (simple) way without eval. If you're concerned about security (because the input you're parsing isn't from a source you control), maybe you can check the input's format (via a whitelist regex filter) before passing it to eval?

查看更多
其实,你不懂
7楼-- · 2018-12-31 12:44

I went looking for JavaScript libraries for evaluating mathematical expressions, and found these two promising candidates:

  • JavaScript Expression Evaluator: Smaller and hopefully more light-weight. Allows algebraic expressions, substitutions and a number of functions.

  • mathjs: Allows complex numbers, matrices and units as well. Built to be used by both in-browser JavaScript and Node.js.

查看更多
登录 后发表回答