(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()))