当前位置: 首页 > 工具软件 > eval5 > 使用案例 >

微信小程序的eval替代方法亲测能用!!

张晔
2023-12-01

学校老师让我们用小程序写计算器,运行的时候发现eval函数用不了,找了很久,也试过装npm,搞了很久,但是一直报错,然后找到了这个。

说明一下——eval函数要少用,不安全,不推荐

复制下面的代码就能直接用了

//测试
console.log(expressionCalc('5+4-2+7*3/2'));  //17.5


var expressionCalc = (function () {

    var operatorTable;

    operatorTable = {
        '-': {
            priority: 1,
            handle: function (a, b) {
                return a - b;
            }
        },
        '+': {
            priority: 1,
            handle: function (a, b) {
                return a + b;
            }
        },
        '*': {
            priority: 2,
            handle: function (a, b) {
                return a * b;
            }
        },
        '/': {
            priority: 2,
            handle: function (a, b) {
                return a / b;
            }
        }
    };

    function postfix(expression) {
        var i, op, stack, output, n, char;

        stack = [];
        output = [];

        //去空白
        expression = expression.replace(/\s/g, '');

        function getn() {
            var n, c;

            n = '';

            while ((c = expression[i]) && /\w/.test(c)) {
                n += c;
                i++;
            }

            i--;

            return n;
        }
        function popstack(tobrace) {
            var o;

            while (stack.length) {
                if (tobrace) {
                    o = stack.pop();
                    if (o == '(') {
                        break;
                    }
                    output.push(o);
                } else if (operatorTable[stack[stack.length - 1]] && operatorTable[stack[stack.length - 1]].priority >= op) {
                    output.push(stack.pop());
                } else {
                    break;
                }
            }
        }

        for (i = 0; i < expression.length; i++) {
            char = expression[i];

            if (char == ")") {
                popstack(true);
            } else if (char == "(") {
                stack.push(char);
            } else if (operatorTable[char] && (op = operatorTable[char].priority)) {
                popstack();
                stack.push(char);
            } else {
                output.push(getn());
            }
        }

        op = -1;
        popstack();

        return output;
    }

    function calcStack(stack) {

        var n1, n2, r, output;

        if (!stack.length) return;

        output = [];

        for (i = 0; i < stack.length; i++) {
            n = stack[i];

            if (operatorTable[n]) {
                n2 = new Number(output.pop());
                n1 = new Number(output.pop());

                output.push(operatorTable[n].handle(n1, n2));
            } else {
                output.push(stack[i]);
            }
        }

        return output[0];
    }

    return function (expression) {
        return calcStack(postfix(expression));
    }
})();


 类似资料: