Study/JS

JavaScript 기초 강의 3편: 배열과 객체 다루기

wawManager 2024. 12. 3. 12:00
728x90

1. 배열(Array)

배열은 여러 개의 데이터를 순서대로 저장할 수 있는 자료 구조입니다. 배열의 요소는 어떤 데이터 타입이든 포함할 수 있으며, 인덱스를 사용하여 접근합니다.

배열 선언과 기본 사용법

// 배열 선언
let fruits = ["apple", "banana", "cherry"];

// 배열 요소 접근
console.log(fruits[0]); // "apple"

// 배열 요소 변경
fruits[1] = "blueberry";
console.log(fruits); // ["apple", "blueberry", "cherry"]

// 배열 길이
console.log(fruits.length); // 3

배열 메서드

JavaScript는 배열을 조작할 수 있는 다양한 메서드를 제공합니다.

1) push()와 pop()

  • push(): 배열의 끝에 요소를 추가
  • pop(): 배열의 마지막 요소를 제거하고 반환
fruits.push("orange");
console.log(fruits); // ["apple", "blueberry", "cherry", "orange"]

let lastFruit = fruits.pop();
console.log(lastFruit); // "orange"
console.log(fruits); // ["apple", "blueberry", "cherry"]

2) shift()와 unshift()

  • shift(): 배열의 첫 번째 요소를 제거하고 반환
  • unshift(): 배열의 시작 부분에 요소를 추가
fruits.unshift("grape");
console.log(fruits); // ["grape", "apple", "blueberry", "cherry"]

let firstFruit = fruits.shift();
console.log(firstFruit); // "grape"
console.log(fruits); // ["apple", "blueberry", "cherry"]

3) splice()와 slice()

  • splice(): 배열의 요소를 추가하거나 제거
  • slice(): 배열의 일부분을 복사하여 새로운 배열을 반환
// 요소 추가
fruits.splice(1, 0, "lemon");
console.log(fruits); // ["apple", "lemon", "blueberry", "cherry"]

// 요소 제거
fruits.splice(2, 1);
console.log(fruits); // ["apple", "lemon", "cherry"]

// 배열 일부분 복사
let newFruits = fruits.slice(1, 3);
console.log(newFruits); // ["lemon", "cherry"]

4) forEach()와 map()

  • forEach(): 배열의 각 요소에 대해 함수를 실행 (반환값 없음)
  • map(): 배열의 각 요소에 대해 함수를 실행하고 새로운 배열을 반환
fruits.forEach(fruit => console.log(fruit)); // 각 요소 출력

let upperFruits = fruits.map(fruit => fruit.toUpperCase());
console.log(upperFruits); // ["APPLE", "LEMON", "CHERRY"]

2. 객체(Object)

객체는 키-값 쌍으로 데이터를 저장할 수 있는 자료 구조입니다. 객체는 복잡한 데이터를 구조화하고 다룰 때 매우 유용합니다.

객체 선언과 기본 사용법

// 객체 선언
let person = {
    name: "John",
    age: 30,
    isStudent: false
};

// 객체 속성 접근
console.log(person.name); // "John"
console.log(person["age"]); // 30

// 속성 추가 및 변경
person.age = 31;
person.city = "Seoul";
console.log(person); // { name: "John", age: 31, isStudent: false, city: "Seoul" }

객체 메서드

객체는 함수와 결합하여 다양한 기능을 구현할 수 있습니다.

let car = {
    brand: "Toyota",
    model: "Corolla",
    year: 2020,
    start: function() {
        console.log("The car has started.");
    }
};

car.start(); // "The car has started."

객체의 반복문

for...in 반복문을 사용해 객체의 속성을 순회할 수 있습니다.

for (let key in person) {
    console.log(`${key}: ${person[key]}`);
}
// name: John
// age: 31
// isStudent: false
// city: Seoul

3. 배열과 객체의 활용 예제

예제: 학생 목록 관리 프로그램

let students = [
    { name: "Alice", age: 20, grade: "A" },
    { name: "Bob", age: 22, grade: "B" },
    { name: "Charlie", age: 23, grade: "C" }
];

// 모든 학생의 이름 출력
students.forEach(student => console.log(student.name));

// 새로운 학생 추가
students.push({ name: "David", age: 21, grade: "A" });
console.log(students);

// 특정 조건을 만족하는 학생 찾기
let topStudent = students.find(student => student.grade === "A");
console.log(topStudent); // { name: "Alice", age: 20, grade: "A" }

4. 배열과 객체의 변형과 활용

1) 배열과 객체 조합

배열 안에 객체가 포함되거나, 객체의 속성값이 배열인 경우도 자주 사용됩니다.

let library = {
    books: [
        { title: "The Great Gatsby", author: "F. Scott Fitzgerald" },
        { title: "To Kill a Mockingbird", author: "Harper Lee" }
    ]
};

library.books.forEach(book => {
    console.log(`${book.title} by ${book.author}`);
});

2) 객체를 배열로 변환

Object.keys(), Object.values(), Object.entries() 메서드를 사용해 객체의 속성을 배열로 변환할 수 있습니다.

let scores = { math: 90, english: 85, science: 88 };

console.log(Object.keys(scores)); // ["math", "english", "science"]
console.log(Object.values(scores)); // [90, 85, 88]
console.log(Object.entries(scores)); // [["math", 90], ["english", 85], ["science", 88]]

요약

이번 강의에서는 JavaScript의 배열과 객체를 다루는 방법을 배웠습니다. 배열과 객체는 데이터를 관리하고 조작하는 데 필수적인 자료 구조이며, 다양한 메서드를 사용해 효율적으로 데이터를 다룰 수 있습니다. 다음 강의에서는 함수의 고급 사용법과 클로저, 콜백 함수를 배우며 JavaScript 프로그래밍 능력을 더욱 심화하겠습니다.

728x90