简体   繁体   中英

Javascript function - converting string argument to operator

Apologies if my question is unclear, wasn't sure how to word it!

I'm trying to create a function that takes two numbers and a string which contains an operator (eg '+', '-', '*', '/').

I've used .valueOf() on the string to extract the operator, however the num1 and num2 arguments do not seem to evaluate to the passed number parameters. Why is this happening?

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


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

If I understand your requirements, you could use eval() to achieve this:

function calculate(num1, operator, num2) {
  return eval(`${num1} ${operator} ${num2}`);
}

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

Alternatively, you could avoid the use of eval() by using a switch block, which 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

The best way to do what you want is with an object that maps operator names to functions.

 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)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM