Quick one regarding why I have to use the syntax I am using, the code I have below works but I don't understand exactly why...
var allQuestionsArray = [
[{question: "This is question 1", answer: 0}],
[{question: "This is question 2", answer: 3}],
[{question: "This is question 3", answer: 2}],
[{question: "This is question 4",answer: 1}]
];
for (i=0; i < allQuestionsArray.length; i++) {
var question = allQuestionsArray[1][0].question;
var possibleAnswers = allQuestionsArray[1][0].answer;
document.getElementById("qnAsked").innerHTML = question;
document.getElementById("answerChoices").innerHTML = possibleAnswers;
}
My query is why do I need to use "allQuestionsArray[1][0].question;" instead of "allQuestionsArray[1].question;" (or "allQuestionsArray[0][1].question;") to retrieve the question value for the second element within 'allQuestionsArray'?
I feel like one of the latter two should work and that my syntax must be wrong somehow but perhaps I'm just misunderstanding how this code functions. Any insights would be greatly appreciated...
2 Answers 2
You are using an array of arrays. If you simply had and array of objects, your second option would work. However, you have an array of arrays that each contain one object. It's like the difference between this:
var array = [ {} , {} , {} , {} , {} ];
and this:
var newAray = [ [{}] , [{}] , [{}] , [{}] ];
You have to use the more complicated way of access for the second one because of the extra layer of wrapping around each element. for example, array[1].question might return correctly, but you have to use something different for the nested array.
newArray[1][0].question
This accesses the second element in the array, which is an array, and then the first element in this array, which is an object, and then accesses the .question property of the object.
1 Comment
You've got an array, which contains lots of arrays, which each contain an object. So for instance allQuestionsArray[1][0].question accesses the first array within allQuestionsArray, and then the first child of the object within it.
[ ]. There's the outer brackets on the first and last line of the declaration, and then you've got[ ]around each object.allQuestionsArray[1][0].questionaccesses the first array withinallQuestionsArray, and then the first child of the object within it.[1]? Wouldn't you want to use[i]instead...?!