javascript - 构建简单的 JavaScript 测验时遇到问题

标签 javascript

伙计们!

我正在尝试使用 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);

谢谢!

最佳答案

您正在查询this,这将是父上下文 - 可能是一个窗口,因为我看不到父函数。您需要改为查找 arr:

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

关于javascript - 构建简单的 JavaScript 测验时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18203025/

相关文章:

javascript - Grunt - 监视新文件夹

javascript - 如何将值从 ui-gmap-windows InfoWindow/Marker 传递到 ui-sref?

javascript - 从 csv 创建具有正确格式的对象

javascript - 如何对非空 json 使用 ng-switch-when?

javascript - 使用nodejs执行shell脚本命令

javascript - ASP.NET AJAX UpdatePanel 的最佳替代解决方案

javascript - 如何在具有特定数据值的替代元素上应用 CSS?

javascript - 使用多个样式表

谷歌浏览器中的javascript XSL

Javascript - 如何从内部异步函数调用内部类函数?