简体   繁体   中英

Can't figure out how to display all elements in an array

var questions = [
    ['Whats 5 + 10? ', 15],
    ['Whats 5 + 15? ', 20],
    ['Whats 5 + 20? ', 25],
]
var questionsCorrect = [];
var questionsIncorrect = [];

var correct = 0;
var incorrect = 0;
var question; 
var answer;
var response; 
var html;

function print(message) {
    document.write(message);
}

for (var i = 0; i < questions.length; i++ ) {
    question = questions[i][0];
    answer = questions [i][1];
    response = parseInt(prompt(question));
    if (response === answer) {
    correct++;
    questionsCorrect = '<br> Answered correctly: </br>' + '<li>' + question + 

**'</li>';
    }   
    }
html = 'You answered ' + correct + ' question(s) correctly';
print(html);

document.write(questionsCorrect);

Beginner here and first time posting to SO so forgive me if I've royally screwed this up. All I'm trying to accomplish here is display the answers the user got correct and incorrect. I do not understand why the array is only returning the last item in that array. I think once I figure this out everything else will fall into place. Thanks in advance for the help!

Based on my comment here is the 'fixed' code:

 var questions = [ ['Whats 5 + 10? ', 15], ['Whats 5 + 15? ', 20], ['Whats 5 + 20? ', 25], ] var questionsCorrect = []; var questionsIncorrect = []; var correct = 0; var incorrect = 0; var question; var answer; var response; var html; function print(message) { document.write(message); } for (var i = 0; i < questions.length; i++) { question = questions[i][0]; answer = questions[i][1]; response = parseInt(prompt(question)); if (response === answer) { correct++; questionsCorrect += '<br> Answered correctly: </br>' + '<li>' + question + '</li>'; } } html = 'You answered ' + correct + ' question(s) correctly'; print(html); document.write(questionsCorrect); 

please see @roccobarbi answer as it addresses the underlying issue and not just this specific issue.

You can do what Adam H mentions under your post, but you are assigning an empty array [], to questionsCorrect, so I assume you want it to be an array. Just "push" your correct answers into it.

questionsCorrect.push('<br> Answered correctly: </br>' + '<li>' + question + '</li>');

and to display it, just do:

document.write(questionsCorrect.join());

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