【问题标题】:How to make a function like calculate(x, y, operator)?如何制作像calculate(x, y, operator)这样的函数?
【发布时间】:2017-08-18 18:48:38
【问题描述】:

如何使这种功能发挥作用?如果我将其称为calculate(2, 4, '*'),它将返回一个字符串'2*4'。我也尝试了parseInt,但没有成功,它只会首先出现在字符串到数字中。

function calculate(x, y, operation) {
  this.number = x + operation + y;
  return this.number;
}

【问题讨论】:

    标签: javascript function calculator


    【解决方案1】:

    只需用想要的运算符创建一个对象,测试该运算符是否存在,然后使用它。

    var operators = {
            '+': function (a, b) { return a + b; },
            '-': function (a, b) { return a - b; },
            '*': function (a, b) { return a * b; },
            '/': function (a, b) { return a / b; }
        },
        calculate = function (val1, val2, sign) {
            if (sign in operators) {
                return operators[sign](val1, val2);
            }
        }
    
    console.log(calculate(6, 7, '*'));

    【讨论】:

    • 这个带有对象的键值映射是一种有趣的方法,但我相信它可能会变成很多代码,但功能很少。我相信有了 ES2015+ 的箭头函数,它会变得更加简洁和有趣。
    【解决方案2】:

    这是一个基本的计算器,您已经编写了所有代码。只是缺少评估。

    注意:请注意,对于简单的计算器,可以使用eval。前提是您出于安全原因没有在某些关键项目等中实现此功能,但如果它用于某些内部使用或分配,它还不错并且非常方便。

    function calculator(x,y,operation){
      this.number=x+operation+y;
      return eval(this.number);
    }
    console.log(calculator(1,2,"+"));
    console.log(calculator(1,2,"-"));
    console.log(calculator(1,2,"*"));
    console.log(calculator(1,2,"/"));

    【讨论】:

    【解决方案3】:

    您的 operation 参数只是一个字符串,而不是真正的运算符。这就是为什么它不能如你所愿。所以,你有一些选择。

    使用评估

    您可以使用eval 函数将字符串作为一段代码动态运行,这样:

    function calculate(x, y, operation) {
      return eval(x + operation + y)
    }
    

    虽然它看起来如此简洁明了,但请记住,对于安全性可维护性来说,这通常是一种不好的做法性能原因 (more about it here)。


    使用条件

    有时最简单的想法是最好的选择:只需使用一些条件。

    function calculate(x, y, operation) {
      if (operation === '+') return x + y
      else if (operation === '-') return x - y
      else if (operation === '*') return x * y
      else if (operation === '/') return x / y
      else if (operation === '%') return x % y
      else if (operation === '**') return x ** y
      else return NaN
    }
    

    这似乎有点重复,但请记住,您不需要处理很多算术运算。其实all the binary arithmetic operators上面都有处理。

    另一种语法是switch case 语句,但它只是一个更冗长的条件结构,想法保持不变。


    使用带有函数的对象

    Nina Scholz' answer 强烈启发的另一种方法是在对象的帮助下将运算符的字符串表示映射到它们的等效函数:

    function calculate(x, y, operation) {
      var operators = {
        '+': function (a, b) { return a + b },
        '-': function (a, b) { return a - b },
        '*': function (a, b) { return a * b },
        '/': function (a, b) { return a / b },
        '%': function (a, b) { return a % b },
        '**': function (a, b) { return a ** b }
      }
    
      return operation in operators ? operators[operation](x, y) : NaN
    }
    

    如果在 ES2015+ 环境 (see the compatibility) 上,箭头函数 可以让它变得非常优雅:

    function calculate(x, y, operation) {
      const operators = {
        '+': (a, b) => a + b,
        '-': (a, b) => a - b,
        '*': (a, b) => a * b,
        '/': (a, b) => a / b,
        '%': (a, b) => a % b,
        '**': (a, b) => a ** b
      }
    
      return operation in operators ? operators[operation](x, y) : NaN
    }
    

    虽然我个人仍然认为简单的条件语句足以满足这种情况,但这种 Object 方法非常有趣,可以稍微展示一下 JavaScript 的灵活性。

    【讨论】:

      【解决方案4】:

      你应该把它分成4种不同的情况:

      calculate: function(x,y,operation){
            switch(operation){
               case "*":
                 this.number = x*y;
                 break;
               case "/":
                 this.number=x/y;
                 break;
               case "+":
                 this.number= x+y;
                 break;
               case "-":
                 this.number= x-y;
                 break;
               default:
                  break;
            }
      
              return this.number;
      }
      

      它也很容易缩放...

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-10-30
        • 1970-01-01
        • 1970-01-01
        • 2023-03-25
        • 1970-01-01
        • 2013-12-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多