我是一名编程新手,正在完成 Treehouse 的测验。我不想只看解决方案,但我被困住了。我想将每个正确的问题存储在一个新数组中,每个错误的问题也存储在一个新数组中,然后打印出来。我的代码会跟踪每个正确和错误的问题,但它只将一个问题保存到每个新数组中,即使多个问题是正确或不正确的。我确信这很简单,但我做错了什么?
var questions = [
['How many states are in the United States?', '50'],
['How many legs does a spider have?', '8'],
['How many continents are there?', '7']
];
function quiz(quizQuestions) {
var counter = 0;
for (var i = 0; i < questions.length; i++) {
var answer = prompt(questions[i][0]);
if (answer === questions[i][1]) {
var correctAnswers = [questions[i][0]];
counter += 1;
} else {
var wrongAnswers = [questions[i][0]];
}
}
print('<h2>You got these questions right</h2>');
print(correctAnswers);
print('<h2>You got these questions wrong</h2>');
print(wrongAnswers);
var printQuestionsRight = '<h3>You got ' + counter + ' questions right</h3>';
print(printQuestionsRight);
}
function print(message) {
document.write(message);
}
quiz(questions);
最佳答案
Use
array
to hold thequestions
than variable
join()
方法将数组的所有元素连接成一个字符串。
var questions = [
['How many states are in the United States?', '50'],
['How many legs does a spider have?', '8'],
['How many continents are there?', '7']
];
var correctAnswers = [];
var wrongAnswers = [];
function quiz(quizQuestions) {
var counter = 0;
for (var i = 0; i < questions.length; i++) {
var answer = prompt(questions[i][0]);
if (answer === questions[i][1]) {
correctAnswers.push([questions[i][0]]);
counter += 1;
} else {
wrongAnswers.push([questions[i][0]]);
}
}
print('<h2>You got these questions right</h2>');
print(correctAnswers.join('<br>'));
print('<h2>You got these questions wrong</h2>');
print(wrongAnswers.join('<br>'));
var printQuestionsRight = '<h3>You got ' + counter + ' questions right</h3>';
print(printQuestionsRight);
}
function print(message) {
document.write(message);
}
quiz(questions);
Fiddle Demo
关于javascript - 简单的 JavaScript 测验数组问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37481171/