簡體   English   中英

簡單的JavaScript測驗數組問題

[英]Simple JavaScript quiz array issue

我是一名編程新手,正在通過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); 

使用array比變量保存questions

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); 

小提琴演示

首先,不要為正確和錯誤的答案重新聲明變量。 每次回答時,將問題推送到變量上:

 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); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM