简体   繁体   中英

How can I access items inside a two-dimensional array?

For a 5-question multichoice quiz, I have a function that displays a question, creates four list items and appends buttons within them.

I need to put the answer choice text in the buttons. I have an array that contains 5 arrays, each containing 4 answer choice strings. I'm struggling to find the right way to do this. I've tried using nested if loops and foreach() and setting the button textContent to the items, but can't seem to get it to work. I need to access the 4 items in the first inner array, then move to the next inner array on each iteration.

Below is what I have that is working so far.


   var list = document.getElementById("list");
   var btn = document.getElementById("start");
   var question = document.getElementById("question")

   var questionArray = 
   [“Question 1”, 
   “Question 2“,
   “Question 3”,
   “Question 4“,
   “Question 5“];

   var answerArray = 
   [[“answer”, "answer", "answer", "answer"], 
   ["answer", "answer", "answer", "answer"],
   ["answer", "answer", "answer", "answer"],
   ["answer", "answer", "answer", "answer"],
   ["answer", "answer", "answer", "answer"]];


function displayQuestion() {
   for (var i=0; i < questionArray.length; i++) {
       question.textContent = questionArray[i];
       createListItems();
       return;
   }
}

function createListItems() {
   for (var j=0; j < answerArray[0].length; j++) {
       var listItem = document.createElement("li");
       list.appendChild(listItem);
       var answerButton = document.createElement("button");
       listItem.appendChild(answerButton);
   }

}

You can achieve it something like this:

function displayQuestion() {
   for (var i = 0; i < questionArray.length; i++) {
      (function(idx) {
         question.textContent = questionArray[idx];
         createListItems(idx);
      })(i);
   }
}

function createListItems(idx) {
   for (var j=0; j < answerArray[idx].length; j++) {
       var listItem = document.createElement("li");
       listItem.appendChild(document.createTextNode(answerArray[idx]));           
       var answerButton = document.createElement("button");
       listItem.appendChild(answerButton);
       list.appendChild(listItem);
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM