[英]In Javascript, simple calculator, not working
I tried to get numbers by prompt(), and also action name.我试图通过 prompt() 和动作名称来获取数字。 But the result is not as expected
但结果并不如预期
i am new to programming.. code:我是编程新手.. 代码:
function add(n1, n2){ return n1 + n2;}
function sub(n1, n2){ return n1 - n2;}
function mult(n1, n2){ return n1 * n2;}
function div(n1, n2){ return n1/n2;}
function calculator(n1, n2, action){
alert(action(n1, n2));
}
calculator(prompt("first no,"), prompt("second No"), prompt("calc"));
Two things you need to do:你需要做两件事:
function add(n1, n2) { return n1 + n2; } function sub(n1, n2) { return n1 - n2; } function mult(n1, n2) { return n1 * n2; } function div(n1, n2) { return n1 / n2; } function calculator(n1, n2, action) { alert(action(n1, n2)); } function findOperation(name) { switch (name) { case "sub": return sub; case "mult": return mult; case "div": return div; case "add": default: return add; } } calculator( parseFloat(prompt("first no,")), parseFloat(prompt("second No")), findOperation(prompt("Operation Name?")) );
I suggest you take time to learn some basics, you can't convert a string to a function call unless you use eval() like this:我建议您花时间学习一些基础知识,除非您像这样使用 eval(),否则您无法将字符串转换为 function 调用:
function add(n1, n2){ return n1 + n2;}
function sub(n1, n2){ return n1 - n2;}
function mult(n1, n2){ return n1 * n2;}
function div(n1, n2){ return n1/n2;}
function calculator(n1, n2, action){
alert(eval(`${action}(${n1}, ${n2})`));
}
calculator(prompt("first no,"), prompt("second No"), prompt("calc"));
But this is really hacky and unsafe code, a better approach would be:但这确实是 hacky 和不安全的代码,更好的方法是:
const ops = {
"add": (n1, n2) => n1 + n2,
"sub": (n1, n2) => n1 - n2,
"mult": (n1, n2) => n1 * n2,
"div": (n1, n2) => n1/n2
}
function calculator(n1, n2, action){
alert(ops[action](parseFloat(n1), parseFloat(n2)));
}
calculator(prompt("first no,"), prompt("second No"), prompt("calc"));
Also notice the parseFloat(), if you keep the parameters as strings you will get:还要注意 parseFloat(),如果你将参数保存为字符串,你会得到:
input: "1", "2", "add"
output: "12"
input: "1", "2", "add"
output: "12"
the calculator function should be:计算器 function 应该是:
function calculator(n1, n2, action){
alert(eval(action+'('+n1+', '+n2+')'));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.