gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:25:02 25 4
gpt4 key购买 nike

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

我的构造函数如下:

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com