简体   繁体   English

如何在 js 上使用 class 随机化数组

[英]How do I randomize an array with a class on a js

please tell me how can I make it so that the questions are randomly shown every time the page is refreshed?请告诉我如何才能使每次刷新页面时随机显示问题? Thanks in advance提前致谢

  Question {
        constructor(text, answers) {
            this.text = text;
            this.answers = answers;
            var questionss = this.text[Math.round((Math.random()))];
            console.log(questionss)
        }

        Click(index) {
            return this.answers[index].value;

        }
    }
const questions =
        [
            new Question("Решите неравенство:lg(2x+3)>lg(x-1)",
                [
                    new Answer("(-3/2;1)", 0),
                    new Answer("(-∞;-4)", 0),
                    new Answer("(1;+∞)", 1),
                    new Answer("(1;+∞)", 0)
                ]),


            new Question("3 + 78 / 2 = ",
                [
                    new Answer("1", 0),
                    new Answer("2", 0),
                    new Answer("3", 1),
                    new Answer("4", 0)
                ]),
            new Question("4 + 098 / 2 = ",
                [
                    new Answer("1", 0),
                    new Answer("2", 0),
                    new Answer("3", 1),
                    new Answer("4", 0)
                ]),
            new Question("08 + -098 / 2 = ",
                [
                    new Answer("1", 0),
                    new Answer("2", 0),
                    new Answer("3", 1),
                    new Answer("4", 0)
                ]),
        ];

I tried many options and nothing worked because I use classes我尝试了很多选项,但没有任何效果,因为我使用类

var questionss = this.text[Math.round((Math.random()))]; You are aware this picks the first or second character of the text string?您知道这会选择文本字符串的第一个或第二个字符吗? Math.random generates a number between 0 included and 1 excluded. Math.random 生成一个介于 0 包含和 1 排除之间的数字。 I'm not sure what you want to do here...我不确定你想在这里做什么......

If you are trying to display every question in a scrambled order, you could put all your questions in an array and use a Fisher-Yates shuffle , and then display them by iterating over the array.如果您试图以打乱的顺序显示每个问题,您可以将所有问题放在一个数组中并使用Fisher-Yates shuffle ,然后通过遍历数组来显示它们。

If you want to pick one question, you'd have to use Math.floor(Math.random() * questionCount) to pick an index for a random question.如果你想选择一个问题,你必须使用Math.floor(Math.random() * questionCount)来选择一个随机问题的索引。

If you want each question to have a 50% chance of appearing, you'd have to do something like this: if (Math.random() < 0.5) { //display the question }如果您希望每个问题都有 50% 的机会出现,则必须执行以下操作: if (Math.random() < 0.5) { //display the question }

Hope this helps!希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM