构建简单的 JavaScript 测验时遇到问题
2013-08-13
339
各位!
我正在尝试使用 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);
谢谢!
2个回答
您正在查询
this
,它将是父上下文 - 可能是
window
,因为我看不到父
function
。您需要改为查找
arr
:
function pickRandomQuestion(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
CodingIntrigue
2013-08-13
由于您调用
pickRandomQuestion
而不是
something.pickRandomQuestion
,因此其中
this
的值为
window
。
将
this
替换为
allQuestions
Quentin
2013-08-13