javascript - 使用构造函数将对象插入数组?

标签 javascript jquery arrays function constructor

我知道我离题太远了,但我找不到任何可以帮助我解决这个问题的读物。我正在尝试使用构造函数创建一个数组,其中包含测验的问题、选择和答案。我不确定将对象插入数组的语法。

我的构造函数如下:

// Create array to traverse(using jQuery) so that on clicking submit, the current question
//is deleted, and the next question in the array is loaded.
var questionsArray = [];

//Contructor Function to create questions and push them to the array
function Question (question, choices, answer){
    this.question = question;
    this.choices = choices;
    this.answer = answer;
    return questionsArray.push();  //This is way off I know, but I'm lost...
}

最佳答案

questionsArray.push(new Question('how?',['a','b','c'],'a'));

在你的问题中,推送似乎是不必要的

function Question (question, choices, answer){
    this.question = question;
    this.choices = choices;
    this.answer = answer;
}

在创建下一个表单时使用 var current_question = questionsArray.shift();,它从数组中取出第一个元素并移动其余元素。或者,使用 questionsArray.pop() 从队列中获取最后一个。

为了递增数组本身,您可以在构造函数中完成 - 您可以使用 questionsArray.push(this); 结束问题函数,但我宁愿使用外部函数来创建问题和将它们插入到这个数组中。

关于javascript - 使用构造函数将对象插入数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34243990/

相关文章:

javascript - 使用 Angular 转换 JSON 文件中的 HTML

javascript - ES6 类/面向对象和事件处理程序

jQuery 获取当前选定的文本

php - array_diff() 删除了太多元素

javascript - React-Native-snap-carousel 检查条件与状态值?

javascript - Firebug 控制台中的对象

javascript - 在可滚动容器中定位绝对下拉列表

javascript - 在垂直滚动时水平移动 div 中的元素

javascript - html2canvas 保存带有扩展名的 Canvas 图像

c - 如何使用 malloc 分配结构数组