-1

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!

2 Answers 2

3

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)];
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Replace this with allQuestions

3 Comments

Since I am passing the arr argument to the function, doesn't [this] refer to [arr] ?
@shinpou No, this always refers to the context, that's why parameters need to be declared in the first place
@shinpou — No, that would be arr or arguments[0]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.