3 回答
TA贡献1982条经验 获得超2个赞
你需要做两件事:
将输入解析为浮点数
映射用户给定的函数名
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?"))
);
TA贡献1943条经验 获得超7个赞
我建议您花时间学习一些基础知识,除非您像这样使用 eval() ,否则您无法将字符串转换为函数调用:
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"));
但这确实是 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"));
还要注意 parseFloat(),如果你将参数保存为字符串,你会得到:
input: "1", "2", "add" output: "12"
TA贡献1798条经验 获得超3个赞
计算器功能应该是:
function calculator(n1, n2, action){
alert(eval(action+'('+n1+', '+n2+')'));
}
添加回答
举报