Evaluating a string as a mathematical expression in JavaScript

前端 未结 16 2056
我在风中等你
我在风中等你 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条回答
  •  梦毁少年i
    2020-11-22 04:24

    const operatorToFunction = {
        "+": (num1, num2) => +num1 + +num2,
        "-": (num1, num2) => +num1 - +num2,
        "*": (num1, num2) => +num1 * +num2,
        "/": (num1, num2) => +num1 / +num2
    }
    
    const findOperator = (str) => {
        const [operator] = str.split("").filter((ch) => ["+", "-", "*", "/"].includes(ch))
        return operator;
    }
    
    const executeOperation = (str) => {
        const operationStr = str.replace(/[ ]/g, "");
        const operator = findOperator(operationStr);
        const [num1, num2] = operationStr.split(operator)
        return operatorToFunction[operator](num1, num2);
    };
    
    const addition = executeOperation('1 + 1'); // ans is 2
    const subtraction = executeOperation('4 - 1'); // ans is 3
    const multiplication = executeOperation('2 * 5'); // ans is 10
    const division = executeOperation('16 / 4'); // ans is 4
    

提交回复
热议问题