본문 바로가기
  • 코딩, 허쌤이 떠먹여 줄게
FrontEnd/Javascript

14장. 실습 문제

by 허쌤 2026. 1. 13.

14장. 실습 문제

이 장에서는 지금까지 배운 JavaScript 기초 내용을 종합적으로 활용하는 실습 문제를 다룹니다.


실습 문제 1: 두 수의 합 계산기

문제

두 수를 입력받아 합을 출력하는 함수를 작성하세요.

요구사항

  • 함수명: add
  • 두 개의 숫자 매개변수를 받음
  • 두 수의 합을 반환
  • 결과를 콘솔에 출력

예시 코드

function add(a, b) {
    return a + b;
}

console.log(add(3, 5));  // 8
console.log(add(10, 20));  // 30

확장 문제

  • 세 개의 수를 더하는 함수를 작성하세요.
  • 배열의 모든 수를 더하는 함수를 작성하세요.

실습 문제 2: 배열 조작

문제

배열에 값을 추가한 후 전체를 출력하는 프로그램을 작성하세요.

요구사항

  • 초기 배열: ['사과', '바나나']
  • '포도'를 배열에 추가
  • 배열의 모든 요소를 출력
  • 배열의 길이를 출력

예시 코드

let fruits = ['사과', '바나나'];

// 값 추가
fruits.push('포도');

// 전체 출력
fruits.forEach(function(fruit) {
    console.log(fruit);
});

// 또는
for (let fruit of fruits) {
    console.log(fruit);
}

// 배열 길이
console.log(`총 ${fruits.length}개의 과일`);

확장 문제

  • 배열에서 특정 값을 제거하는 함수를 작성하세요.
  • 배열의 평균값을 계산하는 함수를 작성하세요.

실습 문제 3: 버튼 클릭 시 텍스트 변경

문제

버튼을 클릭하면 텍스트가 변경되는 웹 페이지를 만드세요.

요구사항

  • HTML에 제목(<h1>)과 버튼(<button>) 추가
  • 버튼 클릭 시 제목 텍스트가 변경됨
  • 여러 번 클릭해도 동작해야 함

HTML 구조

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>텍스트 변경</title>
</head>
<body>
    <h1 id="title">원본 제목</h1>
    <button id="btn">텍스트 변경</button>

    <script>
        const btn = document.getElementById('btn');
        const title = document.getElementById('title');

        btn.addEventListener('click', function() {
            title.textContent = '변경된 제목!';
        });
    </script>
</body>
</html>

확장 문제

  • 클릭할 때마다 다른 텍스트로 변경되도록 하세요.
  • 텍스트 색상도 함께 변경되도록 하세요.

실습 문제 4: 할인 계산기

문제

상품 가격과 할인율을 입력받아 최종 가격을 계산하는 프로그램을 작성하세요.

요구사항

  • 함수명: calculateDiscount
  • 매개변수: price (가격), discountRate (할인율, 0~1 사이)
  • 원가, 할인액, 최종 가격을 객체로 반환
  • 결과를 콘솔에 출력

예시 코드

function calculateDiscount(price, discountRate) {
    const discountAmount = price * discountRate;
    const finalPrice = price - discountAmount;

    return {
        originalPrice: price,
        discountAmount: discountAmount,
        finalPrice: finalPrice
    };
}

const result = calculateDiscount(10000, 0.2);
console.log(`원가: ${result.originalPrice}원`);
console.log(`할인액: ${result.discountAmount}원`);
console.log(`최종 가격: ${result.finalPrice}원`);

확장 문제

  • 회원 등급에 따라 다른 할인율을 적용하세요.
  • 웹 페이지에서 입력받아 계산하도록 하세요.

실습 문제 5: 학생 성적 관리

문제

학생들의 점수를 관리하는 프로그램을 작성하세요.

요구사항

  • 학생 정보 객체 배열 생성
  • 각 학생의 이름, 점수 포함
  • 평균 점수 계산
  • 최고 점수 학생 찾기
  • 합격자(60점 이상) 필터링

예시 코드

let students = [
    {name: '홍길동', score: 85},
    {name: '김철수', score: 92},
    {name: '이영희', score: 78},
    {name: '박민수', score: 55}
];

// 평균 점수
let sum = students.reduce((acc, student) => acc + student.score, 0);
let average = sum / students.length;
console.log(`평균 점수: ${average}`);

// 최고 점수 학생
let topStudent = students.reduce((max, student) => 
    student.score > max.score ? student : max
);
console.log(`최고 점수: ${topStudent.name} - ${topStudent.score}점`);

// 합격자
let passed = students.filter(student => student.score >= 60);
console.log('합격자:');
passed.forEach(student => {
    console.log(`${student.name}: ${student.score}점`);
});

확장 문제

  • 등급(A, B, C, F)을 추가하세요.
  • 웹 페이지에 표로 출력하세요.

실습 문제 6: 할 일 목록 (To-Do List)

문제

할 일을 추가하고 삭제할 수 있는 간단한 할 일 목록을 만드세요.

요구사항

  • 입력 필드와 추가 버튼
  • 할 일 목록 표시
  • 각 항목에 삭제 버튼
  • 빈 입력은 추가하지 않음

HTML 구조

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>할 일 목록</title>
</head>
<body>
    <h1>할 일 목록</h1>
    <input type="text" id="todoInput" placeholder="할 일을 입력하세요">
    <button id="addBtn">추가</button>
    <ul id="todoList"></ul>

    <script>
        const todoInput = document.getElementById('todoInput');
        const addBtn = document.getElementById('addBtn');
        const todoList = document.getElementById('todoList');

        addBtn.addEventListener('click', function() {
            const text = todoInput.value.trim();

            if (text !== '') {
                const li = document.createElement('li');
                li.textContent = text;

                const deleteBtn = document.createElement('button');
                deleteBtn.textContent = '삭제';
                deleteBtn.addEventListener('click', function() {
                    li.remove();
                });

                li.appendChild(deleteBtn);
                todoList.appendChild(li);
                todoInput.value = '';
            }
        });

        // Enter 키로도 추가 가능
        todoInput.addEventListener('keypress', function(event) {
            if (event.key === 'Enter') {
                addBtn.click();
            }
        });
    </script>
</body>
</html>

확장 문제

  • 완료 체크박스 추가
  • 완료된 항목은 취소선 표시
  • 로컬 스토리지에 저장

실습 문제 7: 간단한 계산기

문제

사칙연산을 수행하는 계산기를 만드세요.

요구사항

  • 두 개의 숫자 입력 필드
  • 연산자 선택 (+, -, *, /)
  • 계산 버튼
  • 결과 표시

HTML 구조

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>계산기</title>
</head>
<body>
    <h1>계산기</h1>
    <input type="number" id="num1" placeholder="첫 번째 수">
    <select id="operator">
        <option value="+">+</option>
        <option value="-">-</option>
        <option value="*">×</option>
        <option value="/">÷</option>
    </select>
    <input type="number" id="num2" placeholder="두 번째 수">
    <button id="calculateBtn">계산</button>
    <div id="result"></div>

    <script>
        const num1 = document.getElementById('num1');
        const num2 = document.getElementById('num2');
        const operator = document.getElementById('operator');
        const calculateBtn = document.getElementById('calculateBtn');
        const result = document.getElementById('result');

        calculateBtn.addEventListener('click', function() {
            const a = parseFloat(num1.value);
            const b = parseFloat(num2.value);
            const op = operator.value;

            let answer;
            switch(op) {
                case '+':
                    answer = a + b;
                    break;
                case '-':
                    answer = a - b;
                    break;
                case '*':
                    answer = a * b;
                    break;
                case '/':
                    answer = b !== 0 ? a / b : '0으로 나눌 수 없습니다';
                    break;
            }

            result.textContent = `결과: ${answer}`;
        });
    </script>
</body>
</html>

확장 문제

  • 계산 이력 표시
  • 키보드로도 입력 가능하도록 개선

실습 문제 8: 숫자 맞추기 게임

문제

1부터 100까지의 숫자를 맞추는 게임을 만드세요.

요구사항

  • 랜덤 숫자 생성 (1~100)
  • 사용자가 숫자 입력
  • 높다/낮다 힌트 제공
  • 정답 시 축하 메시지
  • 시도 횟수 표시

예시 코드

let targetNumber = Math.floor(Math.random() * 100) + 1;
let attempts = 0;

function guessNumber(userGuess) {
    attempts++;

    if (userGuess === targetNumber) {
        return `정답입니다! ${attempts}번 만에 맞췄습니다.`;
    } else if (userGuess < targetNumber) {
        return '더 큰 수입니다.';
    } else {
        return '더 작은 수입니다.';
    }
}

// 사용 예시
console.log(guessNumber(50));
console.log(guessNumber(75));

확장 문제

  • 웹 페이지로 구현
  • 최고 기록 저장
  • 힌트 기능 추가

종합 실습: 간단한 주소록

문제

이름, 전화번호, 이메일을 관리하는 주소록을 만드세요.

요구사항

  • 주소록 항목 추가
  • 주소록 목록 표시
  • 항목 삭제
  • 검색 기능

구현 가이드

// 주소록 데이터
let contacts = [];

// 주소록 추가 함수
function addContact(name, phone, email) {
    contacts.push({
        name: name,
        phone: phone,
        email: email
    });
}

// 주소록 표시 함수
function displayContacts() {
    contacts.forEach((contact, index) => {
        console.log(`${index + 1}. ${contact.name} - ${contact.phone} - ${contact.email}`);
    });
}

// 주소록 삭제 함수
function deleteContact(index) {
    contacts.splice(index, 1);
}

// 검색 함수
function searchContact(keyword) {
    return contacts.filter(contact => 
        contact.name.includes(keyword) ||
        contact.phone.includes(keyword) ||
        contact.email.includes(keyword)
    );
}

// 사용 예시
addContact('홍길동', '010-1234-5678', 'hong@example.com');
addContact('김철수', '010-9876-5432', 'kim@example.com');
displayContacts();

확장 문제

  • 웹 페이지로 구현
  • 로컬 스토리지에 저장
  • 수정 기능 추가

문제 해결 팁

1. 문제 분석

  • 문제를 자세히 읽고 요구사항을 파악하세요
  • 입력과 출력을 명확히 하세요
  • 예시를 통해 동작 방식을 이해하세요

2. 단계별 접근

  • 큰 문제를 작은 문제로 나누세요
  • 하나씩 해결해 나가세요
  • 각 단계를 테스트하세요

3. 코드 작성

  • 변수명은 의미 있게 지으세요
  • 주석을 적절히 사용하세요
  • 코드를 간결하게 유지하세요

4. 디버깅

  • console.log()를 활용하세요
  • 브라우저 개발자 도구를 사용하세요
  • 오류 메시지를 자세히 읽으세요

추가 학습 자료

추천 학습 순서

  1. 기본 문법 복습 (1~8장)
  2. 배열과 객체 활용 (9~10장)
  3. DOM 조작과 이벤트 (11~12장)
  4. 고급 개념 (13장)
  5. 실습 문제 풀이 (14장)

다음 단계

  • ES6+ 문법 (템플릿 리터럴, 구조 분해, 전개 연산자 등)
  • 비동기 프로그래밍 (Promise, async/await)
  • 모듈 시스템
  • 프레임워크 학습 (React, Vue 등)

마무리

이 교안을 통해 JavaScript의 기초를 학습했습니다. 이제 다음 단계로 나아갈 준비가 되었습니다!

핵심 요약:

  • ✅ 변수와 데이터 타입
  • ✅ 연산자와 조건문, 반복문
  • ✅ 함수와 배열, 객체
  • ✅ DOM 조작과 이벤트
  • ✅ 스코프와 호이스팅

계속 학습하세요! 실습을 통해 익힌 내용을 확실히 내 것으로 만드세요.

'FrontEnd > Javascript' 카테고리의 다른 글

모바일 메뉴(햄버거메뉴) - 네비  (0) 2026.02.12
JavaScript DOM과 이벤트 완전 정복  (1) 2026.02.06
13장. 스코프와 호이스팅  (0) 2026.01.12
12장. 이벤트 (Event)  (0) 2026.01.11
11장. DOM 조작  (0) 2026.01.10