如何使用变量进行计算

How to do a calculation using a variable

我想做一个给出答案的随机计算生成器。 我的问题是我不会计算。

operating = Math.floor(Math.random() * 2) + 1;
if (operating == 1) {operating = "+";} else {operating = "-";};
nb1 = Math.floor(Math.random() * max);
nb2 = Math.floor(Math.random() * max);
document.getElementById("calculs").innerHTML = nb1 + " " + operating + " " + nb2;
answer = nb1 + operating + nb2;
console.log(answer);

这一行:answer = nb1 + operating + nb2; 不要工作。 document.getElementById("calculs").innerHTML = nb1 + " " + 操作 + " " + nb2;结果是(示例):10 + 10

在这种情况下,变量 answer 是一个字符串。 为了从该字符串中获得正确的结果,您应该使用:

answer = nb1 + operating + nb2;
result = eval(answer);

eval() function for "running" code from a string, which can be a mathematical operation. However also see its dangers on the same page

所以试试吧:

console.log(eval(answer));

而是将计算放在 if 中:

operating = Math.floor(Math.random() * 2) + 1;
nb1 = Math.floor(Math.random() * max);
nb2 = Math.floor(Math.random() * max);
if (operating == 1) {
  operating = "+";
  answer = nb1 + nb2;
} else {
  operating = "-";
  answer = nb1 - nb2;
};
document.getElementById("calculs").innerHTML = nb1 + " " + operating + " " + nb2;
console.log(answer);

假设您基本上希望输出为 20(数字)而不是“10 + 10”(字符串):

const result = operating === 1 ? nb1 + nb2 : nb1 - nb2;

会给你结果。

此外,如果要显示字符串“10 + 10”,请不要使用相同的 operating 变量,因为代码的可读性会降低。所以在这种情况下你可以这样做:

let operatorSymbol;
let result = 0;
const nb1 = Math.floor(Math.random() * max);
const nb2 = Math.floor(Math.random() * max);
const operating = Math.floor(Math.random() * 2) + 1;
if (operating === 1) {
  operatorSymbol = '+';
  result = nb1 + nb2;
} else {
  operatorSymbol = '-';
  result = nb1 - nb2;
}
document.getElementById("calculs").innerHTML = `${nb1} ${operatorSymbol} ${nb2}`;
console.log(result);