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



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

目前正在工作,但我遇到了一个我无法弄清楚的错误。这是我在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*(dWd)/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),它会给你一个错误

类型错误:10 不是函数

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

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

如果要将两个值相乘,则必须使用乘法运算符。

10 * (5+3)

最新更新