Javascript обнаруживает деление (/) как сложение (+) - PullRequest
0 голосов
/ 17 апреля 2019

Я пытаюсь сделать базовый калькулятор на основе 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», как будто он добавляет их вместо этого.

1 Ответ

2 голосов
/ 17 апреля 2019

(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()))
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...