Javascript函数-将字符串参数转换为运算符

时间:2018-08-29 21:38:12

标签: javascript function arguments operators

很抱歉,如果我的问题不清楚,不确定如何措辞!

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

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

HFONT font = CreateFont(pixels_height, 0, // size
                        0, 0, 0, // normal orientation
                        FW_NORMAL,   // normal weight--e.g., bold would be FW_BOLD
                        false, false, false, // not italic, underlined or strike out
                        DEFAULT_CHARSET,
                        OUT_OUTLINE_PRECIS, // select only outline (not bitmap) fonts
                        CLIP_DEFAULT_PRECIS,
                        CLEARTYPE_QUALITY,
                        VARIABLE_PITCH | FF_SWISS,
                        "Arial");

2 个答案:

答案 0 :(得分:2)

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

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

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

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

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

答案 1 :(得分: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));