在JavaScript中将对象放入数组中

时间:2017-01-25 10:38:54

标签: javascript arrays

我目前正在使用MVC JS框架,我希望能够获得一个对象列表,我可以在循环中随机输入。到目前为止,我已经设法创建一个函数,找到一个随机ID并拉出该对象,以便该部分不是问题。这是进入对象数组的内容:

QuestionsSetup: function(gameType) {

        // Setup Resources
        var c = this.View.children;
        var player1qs = [];
        var leftQ = 0;
        var rightQ = 0;
        var maxQValue = 50;
        var minQValue = 1;

        // Fill array with questions 
        for (var i = 0; i < 5; i++) {

            // Build a random question with numbers between 1 and 50

            // Build Question Text to output to user

            // Generate correct answers based on generated question

            // Generate unsorted, incorrect answers and add them to an array

            //Place Questions into object
            questions.qId = i;
            questions.leftQ = leftQ;
            questions.rightQ = rightQ;
            questions.correctAnswer = correctAnswer;
            questions.allAnswers = sortedAnswers;
            questions.questionText = questionText;

            //Add to array of questions
            player1qs.push(questions);
        }
    }

这会将它们添加到一个数组中,但是当添加一个新对象时,它也会更改数组中现有对象的值,因此无论后面我提取哪一个,它们都会变得相同。问题对象在模型文件夹中的自己的文件中声明。在每个循环开始时,有没有办法告诉应用程序我想要新的空问题对象而不是引用现有的问题?我知道你可以使用类似的后端语言,所以我拒绝相信JavaScript中也不存在这么简单的东西吗?

3 个答案:

答案 0 :(得分:1)

确定缺少每个数组项的变量。

QuestionsSetup: function(gameType) {

    // Setup Resources
    var c = this.View.children;
    var player1qs = [];
    var leftQ = 0;
    var rightQ = 0;
    var maxQValue = 50;
    var minQValue = 1;

    // Fill array with questions 
    for (var i = 0; i < 5; i++) {

        var tempQuestion = {
           qId: i,
           leftQ: leftQ,
           rightQ: rightQ,
           correctAnswer: correctAnswer,
           allAnswers: sortedAnswers,
           questionText: questionText
        }


        // ...


        //Add to array of questions
        player1qs.push(tempQuestion);
    }
}

在循环中使用单独的闭包也可能是一个好主意。

答案 1 :(得分:0)

这样做:

for (var i = 0; i < 5; i++) {
   let questions = {};
   // the rest....

您需要先定义对象。

答案 2 :(得分:0)

也许您应该在初始化其属性之前初始化问题对象,因此代码应该如下所示:

       //Place Questions into object
        questions = {};

        questions.qId = i;
        questions.leftQ = leftQ;
        questions.rightQ = rightQ;
        questions.correctAnswer = correctAnswer;
        questions.allAnswers = sortedAnswers;
        questions.questionText = questionText;

        //Add to array of questions
        player1qs.push(questions);