在 window.alert (Javascript) 中分配随机消息

Assign Random Messages in window.alert (Javascript)

我是一名数字艺术专业的学生,​​我在读一年级,最近我们接到任务,要制作一个基本的数学电子学习网站。基本上你被问到(例如)7 乘以 7 是多少,你输入答案并点击一个按钮,一个警报 window 出现。如果你是正确的,它应该说 "correct" 或 "yay" 或 "well done",如果你错了,它应该说 "No" 或 "try again" 或其他。

我的问题是它应该在 window 警报中显示一条随机消息,而不是一次或一条接一条地显示所有消息,只是随机一条消息。我看过但找不到任何有用的东西。

这是我遇到问题的部分代码:

<script type="text/javascript">
    var x, y;
    var answer;



    function aNumber() {

        return Math.floor(1 + (Math.random() * 12));

    }

    function genQuestion() {
        x = aNumber();
        y = aNumber();
        din = document.getElementById("inputVal");
        din.value = x + " times " + y;
        answer = x * y;
    }



    function ClickAnswer() {
        if (answer == document.getElementById("outputVal").value) {
            window.alert("Correct");
            window.alert("Yes!");
            window.alert("Well done");
           location.reload();

        } else {
            window.alert("No, try again.");
            window.alert("try again");
            window.alert("wrong");
        }

    }

    function displayArea() {
        din = document.getElementById("inputVal");
        dout = document.getElementById("outputVal");
        dout.value = circleArea(din.value);
    }

</script>

问题是您是这样同时写所有消息的:

   window.alert("Correct");
   window.alert("Yes!");
   window.alert("Well done");

相反,您可以将消息存储到数组中,从该数组中选取一个随机数和 select 一条消息。你可以尝试这样的事情:

var message = ["Correct","Yes!","Well done"];

var a = Math.floor(Math.random() * message.length);

window.alert(message[a]);

将消息放在一个数组中,并提醒其中的随机条目。

let successMsg = ['Correct', 'Cool'];
let errorMsg = ['Wrong', 'false'];

alert(successMsg[Math.floor(Math.random() * successMsg.length)]);

function ClickAnswer() {
    if (answer == document.getElementById("outputVal").value) {
        alert(successMsg[Math.floor(Math.random() * successMsg.length)]);

       location.reload();

    } else {
        alert(errorMsg[Math.floor(Math.random() * successMsg.length)]);
    }

您要做的是像选择号码一样使用 Math.random()。将每个正确答案分配给一个数组,将每个错误答案分配给另一个数组。然后你可以检索它们:

correct_answers[Math.floor(Math.random()*correct_answers.length)];
imcorrect_answers[Math.floor(Math.random()*incorrect_answers.length)];

我已经创建了原始代码的精简版本,在此处展示了这一点:

var correct_answers = ["Correct", "Yes!", "Well done"];
var incorrecty_answers = ["No, try again.", "try again", "wrong"];

correct_answers[Math.floor(Math.random()*correct_answers.length)];

function ClickAnswer() {
  if (true) {
    window.alert(correct_answers[Math.floor(Math.random()*correct_answers.length)]);
  } else {
    window.alert(incorrect_answers[Math.floor(Math.random()*incorrect_answers.length)]);
  }
}

ClickAnswer();

希望对您有所帮助! :)

您可以采用的一种方法是将要随机化的字符串值存储在一个数组中,然后从中随机选择 return 一个特定索引。看看here.

你的情况可能是

var positiveAnswers= ['Correct!', 'Yes!', 'Well done!'];    
var randomAnswer = positiveAnswers[Math.floor(Math.random() * positiveAnswers.length)];

window.alert(randomAswer);