首页 > 解决方案 > 数学运算作为变量?

问题描述

我正在网页上用 JS 制作计算器,我想知道是否可以做这样的事情:我有 5 个操作按钮,每个按钮都像

<button name="operation" onclick="operation(+)">+</button>
<button name="operation" onclick="operation(-)">-</button>

ETC

然后,在那个函数中,我会有这个:

function operation(n) {
  var num1 = [contents of display]
  var operation = n
}

然后在equals函数中我会有这个。

function equals() {
  var num2 = [contents of display]
  document.getElementById("display").value = num1 operation num2;
}

像'num1 operation num2'这样的可能吗,还是我需要很多单独的功能?

如果您出于某种原因想查看我的计算器的当前状态,请单击此处。(紫色的操作按钮和等号按钮都没有做任何事情,ofc。)

标签: javascript

解决方案


的语法operation(+)不是有效的 javascript。

如果你想以这种方式进行,你应该使用字符串来确定操作,例如:

onclick="operation('+')"

然后在你的函数operation中有类似的东西:

function operation(operator) {
  var num1 = ...
  var num2 = ... // whatever you do to retrieve those values
  if(operator == "+") {
    document.getElementById("display").value = num1 + num2;
  }
  else if (operator == "-") {
    ... // same for -
  }
  // and so on
}

推荐阅读