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);
这里是初学者,也是第一次发给SO,所以请原谅我,如果我已将其弄糟了。我要在这里完成的所有操作都是显示用户正确和不正确的答案。我不明白为什么数组只返回该数组中的最后一项。我认为,一旦我弄清了这一点,其他所有内容都会落到位。预先感谢您的帮助!
答案 0 :(得分:0)
根据我的评论,这里是“固定”代码:
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);
请参阅@roccobarbi答案,因为它解决了根本问题,而不仅仅是这个特定问题。
答案 1 :(得分:0)
您可以执行亚当·H(Adam H)在您的帖子下提到的操作,但是您正在为questionsCorrect分配一个空数组[],所以我假设您希望它是一个数组。只需将正确答案“推入”其中即可。
questionsCorrect.push('<br> Answered correctly: </br>' + '<li>' + question + '</li>');
并显示它,只需执行以下操作:
document.write(questionsCorrect.join());