有问题构建一个简单的JavaScript测验

时间:2013-08-13 07:24:56

标签: javascript

人!

我正在尝试使用JavaScript构建一个基本的测验应用程序,但我遇到了一些“碰撞”

为什么我的代码不在currentQuestion变量中存储allQuestions数组的元素?

这是代码:

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);

谢谢!

2 个答案:

答案 0 :(得分:3)

您正在查询this,这将是父上下文 - 可能是window,因为我看不到父function。您需要反对arr

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

答案 1 :(得分:0)

由于您致电pickRandomQuestion而非something.pickRandomQuestion,其中this的值为window

this替换为allQuestions