我正在尝试使用对象制作一个基于JavaScript的基本计算器。由于某种原因,属性“ calculator.divide”似乎返回了两个数字。
我已经在在线编译器(js.do&code.sololearn.com)和记事本中尝试过此操作,但是它似乎不起作用。
var n1 = +(prompt("Enter 1st number:"));
var n2 = +(prompt("Enter 2nd number:"));
//gets user input & declares variables
//+ for changing string to integer
var calculator = {
add: (n1 + n2), subtract: (n1 - n2), multiply: (n1 * n2), divide: (n1 / n2)
};
var operation = prompt("enter an operation: add, subtract, multiply, or divide");
if (operation = "add") {
document.write(calculator.add);
}
else if (operation = "subtract") {
document.write(calculator.subtract);
}
else if (operation = "multiply") {
document.write(calculator.multiply);
}
else if (operation = "divide") {
document.write(calculator.divide);
}
例如,如果我输入6作为我的第一个数字,输入2作为我的第二个数字,据我了解,当访问“ calculator.divide”时,它将输出“ 3”。似乎并非如此。相反,它输出“ 8”,就好像要添加它们一样。
答案 0 :(得分:2)
(operation = "add")
是错误的,它必须是(operation === "add")
。其余if
都一样。而不是进行比较,它只是分配值
var n1 = +(prompt("Enter 1st number:"));
var n2 = +(prompt("Enter 2nd number:"));
//gets user input & declares variables
//+ for changing string to integer
var calculator = {
add: (n1 + n2),
subtract: (n1 - n2),
multiply: (n1 * n2),
divide: (n1 / n2)
};
var operation = prompt("enter an operation: add, subtract, multiply, or divide");
if (operation === "add") {
document.write(calculator.add);
} else if (operation === "subtract") {
document.write(calculator.subtract);
} else if (operation === "multiply") {
document.write(calculator.multiply);
} else if (operation === "divide") {
document.write(calculator.divide);
}
您可以避免if-else
并使用对象查找
var n1 = +(prompt("Enter 1st number:"));
var n2 = +(prompt("Enter 2nd number:"));
var operation = prompt("enter an operation: add, subtract, multiply, or divide");
function execute(n1, n2, ops) {
calculator = {
add: (n1 + n2),
subtract: (n1 - n2),
multiply: (n1 * n2),
divide: (n1 / n2),
}
return (calculator[ops]);
}
document.write(execute(n1, n2, operation.trim()))
您还可以避免使用内部计算功能
var n1 = +(prompt("Enter 1st number:"));
var n2 = +(prompt("Enter 2nd number:"));
var operation = prompt("enter an operation: add, subtract, multiply, or divide");
function calculator(n1, n2, ops) {
return {
add: (n1 + n2),
subtract: (n1 - n2),
multiply: (n1 * n2),
divide: (n1 / n2),
}[ops];
}
document.write(calculator(n1, n2, operation.trim()))