【发布时间】:2015-05-22 00:55:41
【问题描述】:
我决定用 JavaScript 做一个数学游戏,我对 JS 很陌生。我希望它从数组中选择一个随机操作并用两个随机数对其进行评估,但它不起作用。任何帮助表示赞赏。谢谢!
代码:
var mathGame = function() {
var operators = ["+", "-", "*", "/"];
var operatorChoice = Math.floor((Math.random() * 4) + 1);
var points = 1;
var numberOfQuestions = prompt("How many questions would you like?");
var highestNumber = prompt("What is the highest number you would like to be quizzed on?");
for (var i = 0; i < numberOfQuestions; i++) {
var x = Math.floor((Math.random() * highestNumber) + 1);
var y = Math.floor((Math.random() * highestNumber) + 1);
var answer = (x operators[operatorChoice] y);
var user_answer = prompt(x + operators[operatorChoice] + y);
if (user_answer == answer) {
alert("Yes!");
points = points + 2;
} else {
if (points > 0) {
points = points - 2;
}
alert("Sorry, that was incorrect, the answer is " + answer);
}
}
alert("Your total points were " + points);
};
【问题讨论】:
-
如果您真的想将运算符存储为字符串,可以使用
eval。更好的方法可能是创建一个函数数组并随机选择一个函数(而不是运算符)。 -
究竟什么是“不工作”?你的控制台有什么错误吗?
标签: javascript