개발/Javascript

5일차: 객체와 배열

꿈꾸는법사 2025. 1. 31. 14:46
반응형

이번 5일차에서는 자바스크립트의 객체(Object)배열(Array)을 배우게 됩니다. 객체와 배열은 자바스크립트에서 가장 중요한 자료형으로, 데이터를 구조화하고 관리하는 데 매우 유용합니다.


객체(Object)

자바스크립트에서 객체는 키-값 쌍으로 이루어진 자료형입니다. 객체는 다양한 데이터를 그룹화하여 관리할 수 있는 방법을 제공합니다.

  1. 객체 리터럴 생성

    객체는 중괄호 {}를 사용하여 생성할 수 있습니다. 객체 안에는 속성(Property)값(Value)이 쌍으로 들어갑니다.

    • 객체 생성 예시:
      const person = {
          name: "John",       // 속성: name, 값: "John"
          age: 30,           // 속성: age, 값: 30
          isStudent: false    // 속성: isStudent, 값: false
      };
      console.log(person);
      // 출력: { name: "John", age: 30, isStudent: false }
  2. 객체의 속성 접근 및 수정

    객체의 속성에 접근할 때는 두 가지 방법을 사용할 수 있습니다: 점 표기법(.)과 대괄호 표기법([]).

    • 점 표기법:

      console.log(person.name);  // "John"
      person.age = 31;  // 값을 수정
      console.log(person.age);  // 31
    • 대괄호 표기법:

      console.log(person["isStudent"]);  // false
      person["isStudent"] = true;  // 값을 수정
      console.log(person["isStudent"]);  // true
  3. this 키워드 이해

    this 키워드는 함수 내부에서 현재 객체를 참조하는데 사용됩니다. 일반적으로 객체의 메서드 내에서 사용됩니다.

    • this 사용 예시:
      const person = {
          name: "John",
          age: 30,
          greet: function() {
              console.log(`Hello, my name is ${this.name}.`);  // this.name은 person 객체의 name 속성
          }
      };
      person.greet();  // "Hello, my name is John." 출력

    this는 메서드가 호출될 때 해당 메서드가 속한 객체를 참조합니다.


배열(Array)

배열은 순서가 있는 데이터 집합입니다. 배열은 여러 개의 값을 하나의 변수에 저장할 수 있으며, 배열의 각 값은 인덱스로 접근할 수 있습니다.

  1. 배열 생성과 값 접근

    배열은 대괄호 []를 사용하여 생성하며, 배열의 값은 0부터 시작하는 인덱스를 통해 접근합니다.

    • 배열 생성 예시:
      const numbers = [1, 2, 3, 4, 5];
      console.log(numbers[0]);  // 1 (배열의 첫 번째 요소)
      console.log(numbers[4]);  // 5 (배열의 다섯 번째 요소)
  2. 배열 메서드:

    배열에는 다양한 메서드가 있어 배열을 조작할 수 있습니다. 몇 가지 주요 메서드를 살펴보겠습니다.

    • push(): 배열의 끝에 새로운 요소를 추가합니다.

      numbers.push(6);
      console.log(numbers);  // [1, 2, 3, 4, 5, 6]
    • pop(): 배열의 마지막 요소를 제거하고 그 값을 반환합니다.

      const lastElement = numbers.pop();
      console.log(lastElement);  // 6
      console.log(numbers);  // [1, 2, 3, 4, 5]
    • shift(): 배열의 첫 번째 요소를 제거하고 그 값을 반환합니다.

      const firstElement = numbers.shift();
      console.log(firstElement);  // 1
      console.log(numbers);  // [2, 3, 4, 5]
    • unshift(): 배열의 첫 번째 위치에 새로운 요소를 추가합니다.

      numbers.unshift(0);
      console.log(numbers);  // [0, 2, 3, 4, 5]
  3. 반복문을 이용한 배열 순회

    배열을 반복문으로 순회하여 각 요소에 접근할 수 있습니다. for문, forEach() 메서드를 사용하여 배열을 순회할 수 있습니다.

    • for문 사용 예시:

      const fruits = ["apple", "banana", "cherry"];
      for (let i = 0; i < fruits.length; i++) {
          console.log(fruits[i]);  // "apple", "banana", "cherry" 출력
      }
    • forEach() 메서드 사용 예시:

      fruits.forEach(function(fruit) {
          console.log(fruit);  // "apple", "banana", "cherry" 출력
      });

실습

  1. 간단한 객체 만들기:

    • 목표: 이름, 나이, 직업을 가진 객체를 만들고, 그 값을 수정하거나 출력하는 실습.

    • 예시:

      const student = {
          name: "Alice",
          age: 22,
          major: "Computer Science"
      };
      
      console.log(student.name);  // "Alice"
      student.age = 23;  // 나이 수정
      console.log(student.age);  // 23
  2. 배열 만들기 및 배열 메서드 사용:

    • 목표: 배열을 생성하고, push(), pop(), shift(), unshift() 메서드를 사용하여 배열을 조작하는 실습.

    • 예시:

      const colors = ["red", "green", "blue"];
      colors.push("yellow");  // 배열에 "yellow" 추가
      console.log(colors);  // ["red", "green", "blue", "yellow"]
      
      const removedColor = colors.pop();  // 배열에서 마지막 요소 제거
      console.log(removedColor);  // "yellow"
      console.log(colors);  // ["red", "green", "blue"]
  3. 배열 순회하기:

    • 목표: 배열의 요소를 반복문이나 forEach()를 사용하여 순회하는 실습.

    • 예시:

      const animals = ["dog", "cat", "elephant"];
      animals.forEach(function(animal) {
          console.log(animal);  // "dog", "cat", "elephant" 출력
      });

정리

오늘은 자바스크립트의 객체배열에 대해 배웠습니다. 객체는 다양한 데이터를 속성으로 관리할 수 있는 방법을 제공하며, 배열은 순서 있는 데이터를 처리하는 데 유용합니다. 객체의 속성에 접근하고 수정하는 방법을 익혔고, 배열의 다양한 메서드를 활용하여 배열을 관리하는 방법을 배웠습니다. 실습을 통해 객체와 배열을 만들고, 그 값을 수정하거나 출력해보았습니다.

반응형