Home > database >  For loop only returns last number
For loop only returns last number

Time:06-24

I have made a for loop in order to console log multiple entries in an array. The for loop, however, only returns the last entry in the array, instead of everything from 0 to end of array.

for (var i = 0; i < roa.length; i  ) {questionContentRoa = roa[i].questionContent, correctAnswerRoa = roa[i].correctAnswer }
                console.log(questionContentRoa, correctAnswerRoa);

CodePudding user response:

It will be clearer to you if you ident the code a little bit.

The console.log is outside of the scope, hence, it's only logging the last assignment before the loop ends.

for (var i = 0; i < roa.length; i  ) {
    questionContentRoa = roa[i].questionContent;
    correctAnswerRoa = roa[i].correctAnswer;
}
console.log(questionContentRoa, correctAnswerRoa);

CodePudding user response:

The console.log should be inside the for loop. You have placed it outside.

Alternatively, an easier way to iterate through an array is by using the forEach loop.

roa.forEach((item)=>{
console.log(item.questionContent, item.correctAnswer );
}); 

// in the first iteration item would be the roa[0], 
//then in the second iteration it would be roa[1] and so on until the array ends..

  • Related