【问题标题】:Javascript function - converting string argument to operatorJavascript函数 - 将字符串参数转换为运算符
【发布时间】:2023-09-04 09:36:01
【问题描述】:

抱歉,如果我的问题不清楚,不知道如何措辞!

我正在尝试创建一个函数,该函数接受两个数字和一个包含运算符(例如'+'、'-'、'*'、'/')的字符串。

我在字符串上使用了 .valueOf() 来提取运算符,但是 num1 和 num2 参数似乎没有计算为传递的数字参数。为什么会这样?

function calculate(num1, operator, num2) {
  return `num1 ${operator.valueOf()} num2`;
}
undefined


calculate(2, '+', 1);
"num1 + num2"         //result

【问题讨论】:

  • 如果不使用eval()new Function(),您将无法做您想做的事情,除非您直接检查操作员参数并以适当的方式以编程方式对其进行操作。
  • @Pointy ...但是 eval() 不是邪恶的.....我相信 switch 可以完成这项工作。
  • @gaetanoM 和开关将是该评论的第二部分所指的。

标签: javascript function arguments operators


【解决方案1】:

最好的方法是使用将运算符名称映射到函数的对象。

const opmap = {
  "+": (x, y) => x + y,
  "-": (x, y) => x - y,
  "*": (x, y) => x * y,
  "/": (x, y) => x / y,
};

function calculate(num1, operator, num2) {
  if (operator in opmap) {
    return opmap[operator](num1, num2);
  }
}

console.log(calculate(2, '+', 1));

【讨论】:

    【解决方案2】:

    如果我理解您的要求,您可以使用eval() 来实现:

    function calculate(num1, operator, num2) {
      return eval(`${num1} ${operator} ${num2}`);
    }
    
    console.log(calculate(2, '+', 1)); // 3
    

    或者,您可以通过使用开关块来避免使用eval()would make your code easier to debug and potentially more secure

    function calculate(num1, operator, num2) {
      switch (operator.trim()) { // Trim possible white spaces to improve reliability
        case '+':
          return num1 + num2
        case '-':
          return num1 - num2
        case '/':
          return num1 / num2
        case '*':
          return num1 * num2
      }
    }
    
    console.log(calculate(2, '+', 1)); // 3
    

    【讨论】:

      最近更新 更多