简体   繁体   English

无法弄清楚如何显示数组中的所有元素

[英]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. 这里的初学者和第一次发给SO的人,请原谅,如果我已经把这个问题搞砸了。 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. 请参阅@roccobarbi答案,因为它可以解决根本问题,而不仅仅是这个特定问题。

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. 您可以执行Adam H在您的帖子下提到的操作,但是您正在为questionsCorrect分配一个空数组[],所以我假设您希望它是一个数组。 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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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