Javascript 如何使用变量进行计算
我想做一个随机计算生成器,由它给出答案。 我的问题是我不能计算Javascript 如何使用变量进行计算,javascript,math,calculation,Javascript,Math,Calculation,我想做一个随机计算生成器,由它给出答案。 我的问题是我不能计算 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("calc
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.getElementByIdcalculs.innerHTML=nb1++operating++nb2;结果是示例:10+10在本例中,变量答案是一个字符串。
为了从该字符串中获得正确的结果,应使用:
answer = nb1 + operating + nb2;
result = eval(answer);
在本例中,变量答案是字符串。
为了从该字符串中获得正确的结果,应使用:
answer = nb1 + operating + nb2;
result = eval(answer);
请参阅函数以从字符串运行代码,该字符串可以是数学运算。然而,我们也看到了它的危险性
所以试试看:
console.log(eval(answer));
而是将计算放在if中:
请参阅函数以从字符串运行代码,该字符串可以是数学运算。然而,我们也看到了它的危险性
所以试试看:
console.log(eval(answer));
而是将计算放在if中:
假设您基本上希望输出为20个数字,而不是10+10个字符串:
const result = operating === 1 ? nb1 + nb2 : nb1 - nb2;
我会告诉你结果的
另外,如果您想显示字符串10+10,不要使用相同的操作变量,因为代码可读性较差。因此,在这种情况下,您可以:
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);
假设您基本上希望输出为20个数字,而不是10+10个字符串:
const result = operating === 1 ? nb1 + nb2 : nb1 - nb2;
我会告诉你结果的
另外,如果您想显示字符串10+10,不要使用相同的操作变量,因为代码可读性较差。因此,在这种情况下,您可以:
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);
能否显示行文档的结果。getElementByIdcalculs.innerHTML=nb1++operating++nb2;?答案现在是一个字符串,但您可以对其进行求值,请尝试console.LogEvalanSwer。是否可以显示行文档的结果。getElementByIdcalculs.innerHTML=nb1++operating++nb2;?答案现在是一个字符串,但您可以对其求值,请尝试console.logevalanswer