Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/gwt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用Math.random()进行提问?_Javascript_Random - Fatal编程技术网

Javascript 如何使用Math.random()进行提问?

Javascript 如何使用Math.random()进行提问?,javascript,random,Javascript,Random,所以,我正在制作一个网站,上面有你需要回答的问题,我想按照同样的顺序使用这些问题。那么,我如何使用Math.random()函数将我的问题随机化,而我不想将答案随机化!请使用以下javascript代码提供帮助: (function() { const myQuestions = [{ question: "Esimerkki kysymys1", answers: { a: "Oikein",

所以,我正在制作一个网站,上面有你需要回答的问题,我想按照同样的顺序使用这些问题。那么,我如何使用Math.random()函数将我的问题随机化,而我不想将答案随机化!请使用以下javascript代码提供帮助:

  (function() {
    const myQuestions = [{
            question: "Esimerkki kysymys1",
            answers: {
                a: "Oikein",
                b: "Väärin"
            },
            correctAnswer: "a"
        },
        {
            question: "Esimerkki kysymys2",
            answers: {
                a: "Oikein",
                b: "Väärin"
            },
            correctAnswer: "b"
        },
        {
            question: "Esimerkki kysymys3",
            answers: {
                a: "Oikein",
                b: "Väärin"
            },
            correctAnswer: "a"
        }
    ];

    function Random() {
        var display = document.getElementById("myQuestions");
        var questionAmount = 2;
        for (var i = 0; i < questionAmount; i++) {
            do {
                var randomQuestion = Math.floor(Math.random() * questions.length);
            } while (existingQuestions());

            display.innerHTML += questions[randomQuestion] + '<br>';
            questionTracker.push(randomQuestion);
        }


        function existingQuestions() {
            for (var i = 0; i < questionTracker.length; i++) {
                if (questionTracker[i] === randomQuestion) {
                    return true;
                }
            }
            return false;
        }
    }

    function buildQuiz() {
        // we'll need a place to store the HTML output
        const output = [];

        // for each question...
        myQuestions.forEach((currentQuestion, questionNumber) => {
            // we'll want to store the list of answer choices
            const answers = [];

            // and for each available answer...
            for (letter in currentQuestion.answers) {
                // ...add an HTML radio button
                answers.push(
                    `<label>
     <input type="radio" name="question${questionNumber}" value="${letter}">
      ${letter} :
      ${currentQuestion.answers[letter]}
   </label>`
                );
            }

            // add this question and its answers to the output
            output.push(
                `<div class="slide">
   <div class="question"> ${currentQuestion.question} </div>
   <div class="answers"> ${answers.join("")} </div>
 </div>`
            );
        });

        // finally combine our output list into one string of HTML and put it on the page
        quizContainer.innerHTML = output.join("");
    }

    function showResults() {
        // gather answer containers from our quiz
        const answerContainers = quizContainer.querySelectorAll(".answers");

        // keep track of user's answers
        let numCorrect = 0;

        // for each question...
        myQuestions.forEach((currentQuestion, questionNumber) => {
            // find selected answer
            const answerContainer = answerContainers[questionNumber];
            const selector = `input[name=question${questionNumber}]:checked`;
            const userAnswer = (answerContainer.querySelector(selector) || {}).value;

            // if answer is correct
            if (userAnswer === currentQuestion.correctAnswer) {
                // add to the number of correct answers
                numCorrect++;

                // color the answers green
                answerContainers[questionNumber].style.color = "lightgreen";
            } else {
                // if answer is wrong or blank
                // color the answers red
                answerContainers[questionNumber].style.color = "red";
            }
        });

        // show number of correct answers out of total
        resultsContainer.innerHTML = `${numCorrect} Oikein ${myQuestions.length}`;
    }

    function showSlide(n) {
        slides[currentSlide].classList.remove("active-slide");
        slides[n].classList.add("active-slide");
        currentSlide = n;

        if (currentSlide === 0) {
            previousButton.style.display = "none";
        } else {
            previousButton.style.display = "inline-block";
        }

        if (currentSlide === slides.length - 1) {
            nextButton.style.display = "none";
            submitButton.style.display = "inline-block";
        } else {
            nextButton.style.display = "inline-block";
            submitButton.style.display = "none";
        }
    }

    function showNextSlide() {
        showSlide(currentSlide + 1);
    }

    function showPreviousSlide() {
        showSlide(currentSlide - 1);
    }

    const quizContainer = document.getElementById("quiz");
    const resultsContainer = document.getElementById("results");
    const submitButton = document.getElementById("submit");

    // display quiz right away
    buildQuiz();

    const previousButton = document.getElementById("previous");
    const nextButton = document.getElementById("next");
    const slides = document.querySelectorAll(".slide");
    let currentSlide = 0;

    showSlide(0);

    // on submit, show results
    submitButton.addEventListener("click", showResults);
    previousButton.addEventListener("click", showPreviousSlide);
    nextButton.addEventListener("click", showNextSlide);
})();
(函数(){
常量myQuestions=[{
问题:“Esimerkki Kysmys1”,
答复:{
a:“Oikein”,
b:“Värin”
},
正确答案:“a”
},
{
问题:“Esimerkki Kysmys2”,
答复:{
a:“Oikein”,
b:“Värin”
},
正确答案:“b”
},
{
问题:“Esimerkki Kysmys3”,
答复:{
a:“Oikein”,
b:“Värin”
},
正确答案:“a”
}
];
函数随机(){
var display=document.getElementById(“myQuestions”);
风险价值量=2;
对于(var i=0;i';
问题追踪者:推送(随机问题);
}
函数existingQuestions(){
对于(变量i=0;i{
//我们将要存储答案选择列表
常量answers=[];
//对于每个可用的答案。。。
for(当前问题中的字母。答案){
//…添加一个HTML单选按钮
回答,推(
`
${letter}:
${currentQuestion.answers[字母]}
`
);
}
//将此问题及其答案添加到输出中
输出推送(
`
${currentQuestion.question}
${answers.join(“”}
`
);
});
//最后,将我们的输出列表合并成一个HTML字符串,并将其放在页面上
quizContainer.innerHTML=output.join(“”);
}
函数showResults(){
//从我们的测验中收集答案
const answerContainers=quizContainer.queryselectoral(“.answers”);
//跟踪用户的答案
设numCorrect=0;
//对于每个问题。。。
myQuestions.forEach((当前问题,问题编号)=>{
//查找选定答案
const answerContainer=answerContainers[问题编号];
常量选择器=`input[name=question${questionNumber}]:选中`;
const userAnswer=(answerContainer.querySelector(选择器)| |{}).value;
//如果答案是正确的
如果(userAnswer==currentQuestion.correctAnswer){
//增加正确答案的数量
numCorrect++;
//把答案涂成绿色
answerContainers[questionNumber].style.color=“浅绿色”;
}否则{
//如果答案是错的或是空白的
//把答案涂成红色
回答容器[questionNumber].style.color=“红色”;
}
});
//显示总数中正确答案的数量
resultContainer.innerHTML=`${numCorrect}Oikein${myQuestions.length}`;
}
功能演示幻灯片(n){
幻灯片[currentSlide].classList.remove(“活动幻灯片”);
幻灯片[n]。类列表。添加(“活动幻灯片”);
当前滑动=n;
如果(当前幻灯片===0){
previousButton.style.display=“无”;
}否则{
previousButton.style.display=“内联块”;
}
如果(currentSlide==slides.length-1){
nextButton.style.display=“无”;
submitButton.style.display=“内联块”;
}否则{
nextButton.style.display=“内联块”;
submitButton.style.display=“无”;
}
}
函数showNextSlide(){
放映幻灯片(当前幻灯片+1);
}
函数showPreviousSlide(){
放映幻灯片(当前幻灯片-1);
}
const quizContainer=document.getElementById(“测验”);
const resultcontainer=document.getElementById(“结果”);
const submitButton=document.getElementById(“提交”);
//立即显示测验
buildquick();
const previousButton=document.getElementById(“上一个”);
const nextButton=document.getElementById(“下一步”);
const slides=document.queryselectoral(“.slide”);
设currentSlide=0;
幻灯片(0);
//提交时,显示结果
submitButton.addEventListener(“单击”,显示结果);
previousButton.addEventListener(“单击”,显示PreviousSlide);
addEventListener(“单击”,showNextSlide);
})();
我试着使用Math.random函数,但我无法让它工作

您可以通过使用下面的shuffle函数调用
shuffle(myQuestions)
来设置数组
myQuestions
(Fisher-Yates算法,从链接中的答案复制)

语法:
shuffledArr=shuffle(arr)

然后按顺序显示它们(现在已洗牌)。这将节省空间复杂性,否则将不得不处理一系列已经提出的问题

与OP对话后,以下是完整的重构代码:

下面的示例片段:运行多次以查看不同的结果

函数洗牌(a){
for(让i=a.leng)
function shuffle(a) {
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
}