javascript - 数学运算作为变量?
问题描述
我正在网页上用 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。)
解决方案
的语法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
}
推荐阅读
- node.js - NodeJs Mongoose findById 返回空文档,状态为 true
- angular - Angular 6 上的分页
- jquery - 在 magento 2 中运行 ajax 后消息不起作用(将 form_ui 保存在后端)
- css - 如何防止从父类应用到子类的 CSS 颜色属性
- javascript - 在 Node 的另一个方法中声明的单元测试方法
- php - 在php中使用组合日期和时间对数组数据进行排序
- javascript - Jquery:window.unload 不适用于 chrome 72.0.3626.109
- qt - 在中继器内动态创建 QML 组件
- java - 线程安全对象数组
- c# - 带有 Selenium 的下拉框和 span-Dropdownbox