如何正确地将信息放入数组?

时间:2019-08-15 16:27:28

标签: javascript arrays

UPD :当我单击“生成”按钮:screenshot时,出现一个奇怪的AJAX错误。

我正在做某种测验问题发生器,只是为了好玩:here。问题是我需要在var questionsChoices中创建正确的数组,而且我不知道如何正确循环它。我愿意(您需要查看所有项目以更好地理解=)) 生成的字符串将作为AJAX查询发送到服务器。服务器将生成另一个JS文件,以使测验正常工作。

我尝试将vars更改为 for 循环。

var doc = document;

        // Number of loops is exact 'cuz questions amount always will be not more than 10
        // And only 4 choices

        var questionsText = [];
        var questionsChoices = [[], [], [], []]; // 4 more arrays in array
        var questionsAnswers = [];

        for (var i = 0; i < 10; i++){

            for (var j = 0; j < 4; j++){
                // Include checkbox
                if (doc.getElementById('include' + i).checked){

                    // Grab choices (= ALL answers)
                    // Need to put them in quotes to make correct syntax in generated JS-file
                    questionsChoices[j].push("'" + doc.getElementsByName('right_q' + i)[j].previousElementSibling.value + "'");
                    // Selected radio-button
                    if(doc.getElementsByName('right_q' + i)[j].checked){
                        // Grab questions' text
                        questionsText.push(doc.getElementsByName('q_text' + i)[0].value);
                        // Grab questions' right answer
                        questionsAnswers.push(doc.getElementsByName('right_q' + i)[j].previousElementSibling.value);
                    }
                }
            }
        }


        console.log(questionsChoices);

        // Make data string to send to server via AJAX
        var data = "";
        for (var i = 0; i < questionsText.length; i++){
            // New line + tab in each question
            data += "\n\tnew Question('" + questionsText[i] + "', [" + questionsChoices[i] + "], '" + questionsAnswers[i] + "')";
            // Comma at the end
            data += (i == questionsText.length - 1) ? "" : ",";

        }


        console.log(data);

我希望看到的内容(例如):

new Question('Question 0 Text', ['C00','C01','C02','C03'], 'C00'),
new Question('Question 1 Text', ['C10','C11','C12','C13'], 'C10'),
new Question('Question 2 Text', ['C20','C21','C22','C23', 'C20')

我现在看到的是

new Question('Question 0 Text', ['C00','C10','C20','C40','C50','C70','C80','C90'], 'C00'),
    new Question('Question 1 Text', ['C01','C11','C21','C41','C51','C71','C81','C91'], 'C10'),
    new Question('Question 2 Text', ['C02','C12','C22','C42','C52','C72','C82','C92'], 'C20')

谢谢!

1 个答案:

答案 0 :(得分:0)

我认为您对questionChoices数组的处理方式与其他方式不同。试试这种方法:

var questionsChoices = []; 
for (var i = 0; i < 10; i++){
    questionsChoices.push([]);
    for (var j = 0; j < 4; j++){
        questionsChoices[i].push("'" + doc.getElementsByName('right_q' + i)[?].previousElementSibling.value + "'");
    }
}

PS。当然,您需要相应地调整其余代码。