How do I randomize an array with a class on a js

Viewed 27

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

1 Answers

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. 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.

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.

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 }

Hope this helps!

Related