JS Quiz, random questions

Status
Niet open voor verdere reacties.

hulpbehoefend

Nieuwe gebruiker
Lid geworden
19 jan 2018
Berichten
1
hallo ik moet een quiz maken in JS, maar ik heb een probleem. De vragen moeten in willekeurige volgorde gepresenteerd worden maar dit lukt mij niet. Mijn code is als volgt;
var currentQuestion = 0;
var score = 0;
var totQuestions = questions.length;

var container = document.getElementById('quizContainer');
var questionElement = document.getElementById('question');
var opt1 = document.getElementById('opt1');
var opt2 = document.getElementById('opt2');
var opt3 = document.getElementById('opt3');
var opt4 = document.getElementById('opt4');
var nextButton = document.getElementById('nextButton');
var resultContainer = document.getElementById('result');

function loadQuestion(questionIndex){
var q = questions [questionIndex];
questionElement.textContent =(questionIndex + 1) + '.' + q.question;
opt1.textContent = q.option1;
opt2.textContent = q.option2;
opt3.textContent = q.option3;
opt4.textContent = q.option4;
};
function loadNextQuestion (){
console.log(score);
var selectedOption = document.querySelector('input[type=radio]:checked');
if(!selectedOption){
alert('KIES DAN!');
return;
}
var answer = selectedOption.value;
if(questions[currentQuestion].answer == answer){
score += 1;
}
console.log(answer);
console.log(questions[currentQuestion].answer);
selectedOption.checked = false;
currentQuestion++;
if(currentQuestion == totQuestions - 1){
nextButton.textContent = 'Bekijk je score';
}
if(currentQuestion == totQuestions){
container.style.display = 'none';
resultContainer.style.display = '';
resultContainer.textContent = 'Jouw score: ' + score;
return;
}
loadQuestion(currentQuestion);
}
loadQuestion(currentQuestion);
 
In twee for loops kan je van een lineaire array naar een random array.
Code:
function shuffleQuestions(totalQuestions) {
    // tempArr: 0,1,2,3,.. (tot totalQuestions-1)
    for (var tempArr=[], i=0; i<totalQuestions; i++) {
        tempArr[i] = i;
    }
    // verwijder random van tempArr naar randomArr
    for (var randomArr=[totalQuestions], i=0; i<totalQuestions; i++) {
        randomArr[i] = tempArr.splice(Math.floor(Math.random() * (totalQuestions - i)), 1)[0];
    }
    return randomArr;
}
var totQuestions = 10; //testje
var arr = shuffleQuestions(totQuestions);
// random array zonder dubbele getallen
console.log(arr);
Suc6. Have fun.
 
Status
Niet open voor verdere reacties.
Steun Ons

Nieuwste berichten

Terug
Bovenaan Onderaan