Evaluating a string as a mathematical expression in JavaScript

前端 未结 16 2014
我在风中等你
我在风中等你 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:14

    This is a little function I threw together just now to solve this issue - it builds the expression by analyzing the string one character at a time (it's actually pretty quick though). This will take any mathematical expression (limited to +,-,*,/ operators only) and return the result. It can handle negative values and unlimited number operations as well.

    The only "to do" left is to make sure it calculates * & / before + & -. Will add that functionality later, but for now this does what I need...

    /**
    * Evaluate a mathematical expression (as a string) and return the result
    * @param {String} expr A mathematical expression
    * @returns {Decimal} Result of the mathematical expression
    * @example
    *    // Returns -81.4600
    *    expr("10.04+9.5-1+-100");
    */ 
    function expr (expr) {
    
        var chars = expr.split("");
        var n = [], op = [], index = 0, oplast = true;
    
        n[index] = "";
    
        // Parse the expression
        for (var c = 0; c < chars.length; c++) {
    
            if (isNaN(parseInt(chars[c])) && chars[c] !== "." && !oplast) {
                op[index] = chars[c];
                index++;
                n[index] = "";
                oplast = true;
            } else {
                n[index] += chars[c];
                oplast = false;
            }
        }
    
        // Calculate the expression
        expr = parseFloat(n[0]);
        for (var o = 0; o < op.length; o++) {
            var num = parseFloat(n[o + 1]);
            switch (op[o]) {
                case "+":
                    expr = expr + num;
                    break;
                case "-":
                    expr = expr - num;
                    break;
                case "*":
                    expr = expr * num;
                    break;
                case "/":
                    expr = expr / num;
                    break;
            }
        }
    
        return expr;
    }
    

提交回复
热议问题