2015-12-12 66 views
1

我知道我走了,但我找不到任何阅读,这有助于我解决这个问题。我正在尝试使用构造函数来创建一个充满问题,选择和答案的数组。我不确定将对象推到数组上的语法。使用构造函数将对象推入数组?

我的构造函数如下:

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

'push(...)'接受一个参数。 *你想推什么,新的'Question'实例?你需要传递'this',但实际上最好从构造函数的* outside外调用'questionsArray.push(new Question(...))'。顺便说一句,你不应该从构造函数中返回任何东西。 – Bergi

回答

2

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函数,但我宁愿使用外部函数来创建问题并将它们插入到这个数组中。

+0

这。我不能说更好。 – Bergi