javascript - 如何正确地将信息放入数组?
问题描述
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')
谢谢!
解决方案
我认为您对待 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。当然,您需要相应地调整其余代码。
推荐阅读
- python - 将行添加到多索引 DataFrame
- java - Android Studio 无法启动活动组件信息
- python - Pandas dataframfe TypeError:使用int进行索引有问题吗?
- javascript - 使用订阅将数据保存在 Angular 8 中
- spring - 在 Spring Boot 应用程序启动时清除 Redis 缓存
- c++ - 使用位移获取指数值(C,C++)
- android - 无法下载flutter_embedding_debug.jar
- excel - 根据另一个给定值的最新日期获取值
- python - TypeError:'x' 是 int() 的无效关键字参数
- c++ - 为什么我不能从同一目录中的另一个文件中#include 我的类?