我决定用 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);
};
最佳答案
您可以使用评估:
var answer = eval(x + operators[operatorChoice] + y);
eval
通常不受欢迎,因为如果参数包含用户输入,则可能会很危险。但由于您自己生成所有输入,并且它仅包含列表中的数字和运算符,因此这是对它的合理使用。
处理此问题的更好、更通用的方法是为每个操作定义函数并调用它们。
var mathGame = function() {
function add(x, y) { return x + y; }
function subtract(x, y) { return x - y; }
function multiply(x, y) { return x * y; }
function divide(x, y) { return x / y; }
var operators = ["+", "-", "*", "/"];
var operations = [add, subtract, multiply, divide];
var operatorChoice = Math.floor(Math.random() * operators.length);
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 = operations[operatorChoice](x, 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);
};
mathGame();
Yuo 在您的代码中还存在另一个错误。设置 operatorChoice
时,不应将 1
添加到随机数中。这会产生从 1
到 4
的数字,但 运算符
的索引是 0
到 3
.
关于javascript - 如何让 JavaScript 计算字符串等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30386753/