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



UPD:当我单击"生成"按钮时,出现一个奇怪的AJAX错误:屏幕截图。

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

我试图将变量更改为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 += "ntnew 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')

谢谢!

我认为你对待你的问题选择数组的方式与其他数组不同。请尝试此方法:

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 + "'");
}
}

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

最新更新