Evaluating a string as a mathematical expression in JavaScript

前端 未结 16 2057
我在风中等你
我在风中等你 2020-11-22 03:34

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?

<
16条回答
  •  自闭症患者
    2020-11-22 04:20

    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);
    }
    

提交回复
热议问题