Я пытаюсь создать базовый калькулятор на основе 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 в качестве второго числа, насколько я понимаю, будет выведено «3» при доступе к «calculator.divide». Похоже, это не так. Вместо этого он выводит «8», как будто вместо этого добавляет их.
Привет, добро пожаловать в переполнение стека. Вы должны научиться отлаживать свое приложение, после чего вы сможете самостоятельно исследовать проблему и предоставить больше контекстной информации.



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


(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()))
Вы устанавливаете операцию как «добавить» в своем выражении if