Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Hoang Le
PLUS
Hoang Le
Courses Plus Student 1,274 Points

array only push once

can't get array to push more than once

var questAndAnswer = [ 
  ['1 to 100?', 50],
  ['100 - 1000?' ,500],
  ['1000 - 10000?',5000],
  ['10000 - 100000?',50000]
];
var questions;
var answer;
var respone;
var attempt = 0;
var correctQuest = 0;
var inCorrectQuest = 0;
var html;
var correct = [];
var inCorrect = [];

function buildList(arr)
{ var list = "<ol>";
    for (var i = 0; i < arr.length; i ++ )
{ 
 list += "<li>" + arr[i] + "</li>";
    list += "</ol>";
    return list;

}
                       }
function print(message) {
  var outputBody = document.getElementById('test');
    outputBody.innerHTML = message;


}
for ( var i = 0; i < questAndAnswer.length; i++ ){
    questions= questAndAnswer[i][0];
    answer = questAndAnswer[i][1];
    respone = parseInt(prompt(questions));
    attempt ++;  
if ( respone === answer ) {
    correct.push(questions);
  correctQuest += 1 ;
      }
else {
    inCorrect.push(questions);
    inCorrectQuest += 1;
  }
}
html = " You have answered " + attempt + " questions and guessed " +correctQuest + " questions right !!! " + inCorrectQuest + " questions wrong !!!" ;
html += '<h2> You have answered these question right!!!</h2>';
html += buildList(correct);
html += '<h2> You have answered these question wrong!!!</h2>';
html += buildList(inCorrect);
print(html);

1 Answer

Steven Parker
Steven Parker
229,744 Points

The push function works exactly as expected.

But your buildList function does a return inside the loop, so no matter how long the list is, it will only process the first item.

You probably want to move the closing of the ol and the return outside of the loop.

Hoang Le
Hoang Le
Courses Plus Student 1,274 Points

i tried outside the loop, but it doesn work too

Steven Parker
Steven Parker
229,744 Points

Really? Maybe we had a different idea of where "outside the loop" is. Here's what I meant:

function buildList(arr) {
    var list = "<ol>";
    for (var i = 0; i < arr.length; i++) {
        list += "<li>" + arr[i] + "</li>";
    }
    list += "</ol>"; // moved outside the loop
    return list;     // same here
}