使用for循环检查多个变量的内容

时间:2019-01-22 17:47:39

标签: javascript for-loop variables arguments var

我有多个包含一个问题的数组变量和两个答案选项。它们用于更改问题的调查。

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参数的左侧,我也尝试过:

if (qi = ["","",""]) {

但是,它将选择第一个可用选项(1)。使用==或===使qi不确定。如何通过for循环检查所有数组变量是否为空?我需要一种方法,在每次循环运行时增加第二个数字,然后将其读取为变量。

我可以用很长的if句来做,但是如果我有更多的问题,那会很痛苦。

2 个答案:

答案 0 :(得分:2)

您不能真正地“动态”遍历这样的变量。我会尝试将所有问题放在一个数组中,然后将每个问题及其答案放入一个对象中:

<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)
}

答案 1 :(得分:0)

您可以检查数组的内容以查看其是否包含空字符串,为此,我使用了join将所有空字符串附加并合并为一个,然后与空字符串引用进行比较。

一旦我们发现一个空字符串出现,我们就停下来退出循环,并在遇到空数组的地方打印第i个问题。假设您以有序方式传递问题数组,以使具有空字符串的问题数组位于末尾。

var q1 = ["question","option1","option2"];
var q2 = ["question","option1","option2"];
var q3 = ["","",""];
var q4 = ["","",""];
var questions = [q1, q2, q3, q4];

function checkQuestions(questions){
 for(let i =0; i<questions.length;i++){
   if(questions[i].join("") === ""){
      console.log("stopped at question "+(i+1));
      break;
    }
  } 
}
checkQuestions(questions);