【问题标题】:Using a constructor function to push objects onto an array?使用构造函数将对象推送到数组上?
【发布时间】:2015-12-12 19:25:15
【问题描述】:

我知道我很遥远,但我找不到任何可以帮助我解决这个问题的阅读材料。我正在尝试使用构造函数来创建一个包含问题、选择和答案的数组以进行测验。我不确定将对象推送到数组上的语法。

我的构造函数如下:

// 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...
}

【问题讨论】:

  • push(…) 接受一个参数。 要推送什么,新的Question 实例?您需要传递this,但实际上最好从构造函数的外部 调用questionsArray.push(new Question(…))。顺便说一句,您不应该 return 构造函数中的任何内容。

标签: javascript jquery arrays function constructor


【解决方案1】:

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); 结束 Question 函数,但我更愿意使用外部函数来创建问题并将它们插入到此数组中。

【讨论】:

  • 这个。我不能说得更好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-20
相关资源
最近更新 更多