简单的 JavaScript 测验数组问题
2016-05-27
433
我是编程新手,正在做 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);
2个回答
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 演示
Rayon
2016-05-27
首先,不要为正确和错误答案重新声明变量。每次回答问题时,将问题推送到变量上:
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']
],
correctAnswers = [],
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);
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);
Neil Cooper
2016-05-27