温馨提示:本文翻译自stackoverflow.com,查看原文请点击:javascript - How to do a calculation using a variable
calculation javascript math

javascript - 如何使用变量进行计算

发布于 2020-04-10 00:06:56

我想做一个给出答案的随机计算生成器。我的问题是我无法进行计算。

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

这条线:答案= nb1 +操作+ nb2; 不要工作 document.getElementById(“ calculs”)。innerHTML = nb1 +“” +操作+“” + nb2; 结果是(示例):10 + 10

查看更多

提问者
Nano Geek
被浏览
76
tevemadar 2020-02-01 18:28

请参阅eval()用于从字符串“运行”代码的函数,该函数可以是数学运算。但是在同一页面上也可以看到其危险

所以尝试一下:

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