Javascript Eval()认为第一个值是一个函数

时间:2017-10-24 09:21:05

标签: javascript html regex angular eval

我正在编写一个函数,它将在输入字段中计算表达式并返回总和。

目前正在运作,但我遇到了一个我无法弄清楚的错误。 Here是我在Plunker中的代码。

function linkFunction(scope) {
    var PO = 10;
    scope.value = PO;
    scope.result = '';

    scope.Evaluate = function (input) { 
        if (input.match(/[a-zA-Z]/g) != null) { //to check if user has inputted a letter between a-z, case sensitive.
            return alert("You must only use numbers, not letters")
        } else if (input.match(/[!"^£$&[{}\]?\\@#~<>_'|`¬:;,=]/g) != null) { //to check if user has inputted a special symbol 
            return alert("You must only use the symbols specified")
        } else if (input.match(/\.\d*\.+/g) != null) { //to check if user has inputted a doubled decimal eg 10.2.2
            return alert("You can only use 1 decimal point")
        } else if (input.match(/\.{2,}/g) != null) {//to check if user has inputted a two decimals eg 10..1
            return alert("You cannot put two decimals one after another")
        }

        // if (input.match(/\d*\(\d\W\d\)/g) != null){

        // }

        var percentPattern = /[0-9]*\.?[0-9]+%/g; 
        var expressionResults = input.match(percentPattern);
        if (scope.enablePercentage) { //if parameter = 1, then do this code.
            if (expressionResults != null) { //if user has entered into the input field
                if (expressionResults.length > 1) { //if you user has finished the RegEx (%, is the end of the RegEx, so code will think its the end of the array, therefore you cannot add another %)
                    return alert("Too many % values");
                } else {// user has met all requirements
                    var percentageValue = parseFloat(expressionResults) * PO / 100;
                    input = input.replace(expressionResults, percentageValue);
                }
            }
        } else if (expressionResults != null) { //if parameter = 0, then do this code. Parameter is off, but user has entered percentage
            return alert("You cannot use %");
        }

        scope.result = eval(input);
    }

}});

如果你写10(5 + 3)它会给你一个错误

  

TypeError:10不是函数

显然,如果用户运行此代码,他们希望看到值80。 Eval认为10()是一个函数。 有谁知道如何解决这个问题。感谢

1 个答案:

答案 0 :(得分:1)

eval希望你传递JavaScript,而不是代数。

如果要将两个值相乘,则必须使用Multiplicative Operator

10 * (5+3)