如何使JavaScript评估字符串等

时间:2015-05-22 00:55:42

标签: javascript

我决定用JavaScript制作一个数学游戏,我对JS很新。我希望它从数组中选择一个随机操作并用两个随机数进行评估,但它不起作用。任何帮助表示赞赏。谢谢!

CODE:

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

1 个答案:

答案 0 :(得分:2)

您可以使用eval:

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在您的代码中还有另一个错误。在设置1时,不应将operatorChoice添加到随机数。这会生成从14的数字,但operators的索引为03

相关问题