작동 방식
퀴즈를 구성하게 돼. 질문 하나, 선택지 3개, 클릭하여 답변하면 마지막에 점수가 표시돼. 퀴즈 데이터(질문 및 답변)는 객체 배열에 저장돼. 듣기에는 그럴듯해 보이지만 깔끔하게 정리된 목록임을 알 수 있어.
보여줄게: 퀴즈 데이터
const questions = [
{
text: "How many legs does a spider have?",
choices: ["6", "8", "10"],
correct: 1,
},
{
text: "Which animal is the fastest?",
choices: ["cheetah", "falcon", "hare"],
correct: 1,
},
{
text: "What's the name of our website?",
choices: ["Code with Martin", "Code with Charlie", "Web with Wendy"],
correct: 0,
},
];
- 배열
[...]값의 목록야. 이전에도 알고 계셨겠지만(photos또한 배열이었어). - 객체
{...}이름이 지정된 구획이 있는 상자야.text,choices,correct. -correct: 1의미: 선택 번호 1이 정확해 – 계산은 0부터 시작하므로 순서대로 두 번째야.
보여줄게: 퀴즈 엔진
HTML:
<div class="card">
<h2 id="quiz-question"></h2>
<div id="quiz-choices"></div>
<p id="quiz-status"></p>
</div>
자바스크립트:
const questionEl = document.getElementById("quiz-question");
const choicesEl = document.getElementById("quiz-choices");
const statusEl = document.getElementById("quiz-status");
let questionNumber = 0;
let points = 0;
function showQuestion() {
const question = questions[questionNumber];
questionEl.textContent = question.text;
choicesEl.innerHTML = ""; // clear the old buttons
question.choices.forEach((choice, index) => {
const button = document.createElement("button");
button.textContent = choice;
button.addEventListener("click", () => answer(index));
choicesEl.appendChild(button);
});
statusEl.textContent = "Question " + (questionNumber + 1) + " of " + questions.length;
}
function answer(index) {
if (index === questions[questionNumber].correct) {
points++;
}
questionNumber++;
if (questionNumber < questions.length) {
showQuestion();
} else {
questionEl.textContent = "Done! 🎉";
choicesEl.innerHTML = "";
statusEl.textContent = "You scored " + points + " out of " + questions.length + " points.";
}
}
showQuestion();
새로운 내용:
document.createElement("button")– JavaScript는 요소를 찾을 수 있을 뿐만 아니라 요소를 생성할 수도 있어. 우리는 모든 선택에 대해 버튼을 만듭니다.appendChild(...)– 생성된 요소를 페이지에 삽입해.innerHTML = ""– 요소의 내용을 비웁니다(다음 질문 전에 이전 버튼을 지웁니다).- 두 함수가 서로 작업을 전달해.
showQuestion()무승부,answer()평가해. 프로그램을 작은 기능으로 나누는 것은 프로의 습관야.
네 차례 💪
최소 5개의 자신만의 질문으로 퀴즈를 만드세요. 프로젝트 아이디어:
- 🏫 우리 학교에 관한 퀴즈 – 학교는 몇 년이나 되었나요? 교장은 누구야?? 우리 교실은 몇 개 있나요?
- 🙋 나를 얼마나 잘 아시나요? – 내가 가장 좋아하는 음식은? 나는 몇 살야?? 내 개 이름은 무엇야??
- 🌍 여행 퀴즈 – 크로아티아의 수도? 너 나라에서 가장 높은 산은요? 바다는 어느 방향인가요?
- ⚽ 우리 팀을 얼마나 잘 아시나요? – 주장은 누구인가요? 톰은 몇 골을 넣었나요? 클럽 색상은 무엇야??
내용만 바꿔보세요questions배열 – 퀴즈 엔진은 동일하게 유지돼. 이것이 바로 데이터와 로직이 분리되어 유지되는 이유야!
보너스: 답변에 대한 컬러 피드백
녹색으로 깜박이는 정답을 원하시나요? 조정하다`answer`따라서 먼저 버튼의 색상을 지정하고 잠시 후에 다음 질문을 표시해.function answer(index) {
const buttons = choicesEl.querySelectorAll("button");
const correct = questions[questionNumber].correct;
buttons[correct].style.backgroundColor = "#16a34a";
if (index !== correct) {
buttons[index].style.backgroundColor = "#dc2626";
} else {
points++;
}
setTimeout(() => {
questionNumber++;
if (questionNumber < questions.length) {
showQuestion();
} else {
questionEl.textContent = "Done! 🎉";
choicesEl.innerHTML = "";
statusEl.textContent = "You scored " + points + " out of " + questions.length + " points.";
}
}, 1000);
}
setTimeout(() => {...}, 1000)”1000밀리초 후에 실행”을 의미해. 그리고style.backgroundColorCSS를 JavaScript에서 직접 변경해.
✅
**직접 확인해 보세요:** 퀴즈는 차례로 질문하고 점수를 기록하며 마지막에 결과를 보여줍니다. 방금 첫 번째 실제 애플리케이션을 작성했어. 여기에는 데이터, 로직 및 사용자 인터페이스가 포함되어 있어.
이번 수업에서 배울 점
- 데이터(객체 배열)를 논리(함수)와 분리하여 유지해. 그런 다음 질문을 바꾸는 것만으로 새 퀴즈를 얻을 수 있어.
- JavaScript는 요소를 생성할 수 있어:
createElement+appendChild. -setTimeout지연 후 코드를 실행해.
© 2026 Ing. Martin Polak / AlgoRhino · 콘텐츠 이용 약관