0

伙计们!

我正在尝试使用 JavaScript 构建一个基本的测验应用程序,但遇到了一个小问题

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

这是代码:

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

谢谢!

4

2 回答 2

3

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

function pickRandomQuestion(arr) {
    return arr[Math.floor(Math.random() * arr.length)];
}
于 2013-08-13T07:26:42.933 回答
0

既然你打电话pickRandomQuestion而不是,那么里面something.pickRandomQuestion的价值就是。thiswindow

替换thisallQuestions

于 2013-08-13T07:26:50.170 回答