简体   繁体   中英

Having issues building a simple JavaScript Quiz

guys!

I am trying to build a basic quiz application using JavaScript and I came across a little "bump"

Why doesn't my code store an element of the allQuestions array in the currentQuestion variable ?

This is the code:

var allQuestions = [
            {question: 'What is the first letter of the alphabet?',
             choices: ['a', 'b', 'c', 'd'],
             correctAnswer: 0
            },
            {
             question: 'What is the second letter of the alphabet?',
             choices: ['a', 'b', 'c', 'd'],
             correctAnswer: 1    
            },
            {
             question: 'What is the third letter of the alphabet?',
             choices: ['a', 'b', 'c', 'd'],
             correctAnswer: 2    
            },
            {
             question: 'What is the last letter of the alphabet?',
             choices: ['a', 'b', 'c', 'z'],
             correctAnswer: 3    
            }];

var currentQuestion = {};

function pickRandomQuestion(arr) {
    return this[Math.floor(Math.random() * this.length)];
}

currentQuestion = pickRandomQuestion(allQuestions);

Thank you!

You are querying this , which would be the parent context - presumably a window since I can't see a parent function . You need to look up against arr instead:

function pickRandomQuestion(arr) {
    return arr[Math.floor(Math.random() * arr.length)];
}

Since you call pickRandomQuestion and not something.pickRandomQuestion , the value of this inside it is window .

Replace this with allQuestions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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