首页 > 解决方案 > 如何正确地将信息放入数组?

问题描述

UPD:当我点击“生成”按钮时出现一个奇怪的 AJAX 错误:截图

我正在做一些测验问题生成器只是为了好玩:这里。问题是我需要在 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')

谢谢!

标签: javascriptarrays

解决方案


我认为您对待 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。当然,您需要相应地调整其余代码。


推荐阅读