【问题标题】:Javascript Eval() thinks first value is a functionJavascript Eval() 认为第一个值是一个函数
【发布时间】:2017-10-24 09:21:05
【问题描述】:

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

目前正在工作,但我遇到了一个我无法弄清楚的错误。 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() 是一个函数。 有谁知道如何解决这个问题。谢谢

【问题讨论】:

  • 10(5+3) 不是 javascript 的有效数学表达式。应该是10*(5+3)
  • 您正在考虑文字数学,就像您自己编写的那样。除非您编写逻辑来告诉它要做什么,否则计算机非常愚蠢。您需要编写 10 * (5 + 3) 以便 JavaScript 理解并为您提供结果 80
  • 该代码实际上来自地狱。应该更容易和更具可读性......
  • 你这样做是为了好玩,还是为了学习?如果你打算在生产中使用,你可能想试试mathjs.org
  • 感谢您的回复范围。我将把它用于生产。 mathjs.org 将解决我的问题。

标签: javascript html regex angular eval


【解决方案1】:

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

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

10 * (5+3)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-14
    • 1970-01-01
    • 2020-11-18
    • 2019-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-24
    相关资源
    最近更新 更多