我有多个数组变量,其中包含一个问题和两个答案选项。它们用于更改问题的调查。
var q1 = ["question","option1","option2"];
var q2 = ["question","option1","option2"];
...
var q8 = ["","",""];
var q9 = ["","",""];
我希望能够自动更改用户完成的问题数量。我将这样做的方法是添加一个 for 循环来检查数组是否为空,如果数组为空,它将完成之前问题的调查。
这是我尝试过的:
for (i = 1; i < 9; i++) {
if ("q"+i = ["","",""]) {
console.log("Stopped at "+i);
finishSurvey():
i = 9; //Stop for-loop
} else {
console.log("Error");
}
}
这里的问题是if-argument的左边,我也试过这个:
if (qi = ["","",""]) {
然而,它将选择第一个可用选项 (1)。使用 == 或 === 使 qi 未定义。如何使用 for 循环检查所有数组变量是否为空?我需要一种方法来在每次循环运行时增加第二个数字,然后将其作为变量读取。
我可以用很长的 if 语句来做到这一点,但如果我有更多的问题,那就很痛苦了。
最佳答案
你不能像那样真正“动态地”循环变量。我会尝试将所有问题放在一个数组中,然后将每个问题连同它们的答案放在一个对象中:
<div id="root"></div>
var questions = [
{
question: "question 1",
answers: [
"answer 1",
"answer 2"
]
},
{
question: "question 2",
answers: [
"answer 1",
"answer 2"
]
},
{
question: "question 3",
answers: [
"answer 1",
"answer 2"
]
}
];
function renderQuestions(questionsArr) {
var html = '';
var container = document.getElementById("#root");
quesaionsArr.forEach(function(questionObj) {
if (questionObj.question && questionObj.answers.length) {
// do your work to create each question and answer
}
});
// append final html to parent
container.appendChild(html)
}
关于javascript - 使用for循环检查多个变量的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54313806/