Files
javascript-examples/doc/07_객체와_배열.md
2025-01-26 02:15:33 +09:00

5.6 KiB

객체와 배열

자바스크립트에서 객체와 배열은 데이터를 저장하고 관리하는 데 사용되는 두 가지 기본적인 데이터 구조입니다.

  • **객체(Object)**는 키-값 쌍으로 데이터를 저장합니다.
  • **배열(Array)**은 순서가 있는 리스트로 데이터를 저장합니다.

객체(Object)

객체는 키-값 쌍(key-value pair)으로 구성된 데이터 구조입니다.

  • 키는 문자열 또는 심볼로, 고유한 식별자 역할을 합니다.
  • 값은 키에 할당된 데이터로, 어떤 데이터 타입도 가능합니다.

객체 생성

객체 리터럴 방식

const person = {
  name: "홍길동",
  age: 25,
  isStudent: true,
};

Object 생성자 방식

const car = new Object();
car.brand = "Tesla";
car.model = "Model S";
car.year = 2023;

객체 속성에 접근하기

객체의 속성에 접근하는 방법은 두 가지입니다.

점 표기법 (Dot Notation)

console.log(person.name); // 출력: 홍길동

대괄호 표기법 (Bracket Notation)

대괄호 표기법은 키가 동적으로 결정될 때 유용합니다.

console.log(person["age"]); // 출력: 25

객체의 속성 추가, 수정, 삭제

  • 속성 추가
person.gender = "남성";
console.log(person.gender); // 출력: 남성
  • 속성 수정
person.age = 30;
console.log(person.age); // 출력: 30
  • 속성 삭제
delete person.isStudent;
console.log(person.isStudent); // 출력: undefined

메서드

객체는 함수도 값으로 가질 수 있으며, 이를 메서드라고 합니다.

const calculator = {
  add: function (a, b) {
    return a + b;
  },
  subtract(a, b) {
    return a - b;
  }, // 최신 문법 (ES6)
};

console.log(calculator.add(5, 3)); // 출력: 8
console.log(calculator.subtract(5, 3)); // 출력: 2

객체 순회

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

for (const key in person) {
  console.log(`${key}: ${person[key]}`);
}
// 출력:
// name: 홍길동
// age: 30
// gender: 남성

배열(Array)

배열은 순서가 있는 리스트로, 여러 값을 하나의 변수에 저장할 수 있습니다.

배열의 각 값은 **요소(element)**라고 하며, 0부터 시작하는 인덱스를 가집니다.

배열 생성

배열 리터럴 방식

const fruits = ["사과", "바나나", "포도"];

Array 생성자 방식

const numbers = new Array(1, 2, 3, 4, 5);

배열 요소에 접근하기

배열 요소는 인덱스를 사용하여 접근합니다.

console.log(fruits[0]); // 출력: 사과
console.log(fruits[2]); // 출력: 포도

배열 요소 추가, 수정, 삭제

  • 추가
fruits.push("오렌지"); // 배열 끝에 추가
console.log(fruits); // 출력: ["사과", "바나나", "포도", "오렌지"]

fruits.unshift("딸기"); // 배열 앞에 추가
console.log(fruits); // 출력: ["딸기", "사과", "바나나", "포도", "오렌지"]
  • 수정
fruits[1] = "키위";
console.log(fruits); // 출력: ["딸기", "키위", "바나나", "포도", "오렌지"]
  • 삭제
fruits.pop(); // 배열 끝 요소 삭제
console.log(fruits); // 출력: ["딸기", "키위", "바나나", "포도"]

fruits.shift(); // 배열 앞 요소 삭제
console.log(fruits); // 출력: ["키위", "바나나", "포도"]

메서드

  • forEach() : 배열의 각 요소에 대해 반복 작업을 수행합니다.
fruits.forEach(fruit => console.log(fruit));
// 출력:
// 키위
// 바나나
// 포도
  • map() 배열의 각 요소를 변환하여 새로운 배열을 생성합니다.
const upperFruits = fruits.map(fruit => fruit.toUpperCase());
console.log(upperFruits); // 출력: ["키위", "바나나", "포도"]
  • filter() 조건을 만족하는 요소만 반환합니다.
const filteredFruits = fruits.filter(fruit => fruit.length > 2);
console.log(filteredFruits); // 출력: ["바나나", "포도"]
  • reduce() 배열의 요소를 누적하여 하나의 값으로 반환합니다.
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 출력: 15 

배열 순회

  • for...of : for...of문을 사용하여 배열을 순회할 수 있습니다.
for (const fruit of fruits) {
  console.log(fruit);
}
// 출력:
// 키위
// 바나나
// 포도
  • 전통적인 for문
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}
// 출력:
// 키위
// 바나나
// 포도

객체와 배열의 결합

객체와 배열은 종종 함께 사용됩니다. 예를 들어, 객체의 배열을 만들어 데이터를 관리할 수 있습니다.

const users = [
  { id: 1, name: "홍길동", age: 25 },
  { id: 2, name: "김영희", age: 30 },
  { id: 3, name: "이철수", age: 28 },
];

users.forEach(user => console.log(user.name));
// 출력:
// 홍길동
// 김영희
// 이철수

구조분해할당 (destructing)

구조 분해 할당은 배열이나 객체의 속성을 분해하여 각각의 값을 개별 변수에 할당하는 자바스크립트의 편리한 문법입니다.

const colors = ['red', 'green', 'blue'];
const [firstColor, secondColor] = colors;

console.log(firstColor); // 'red'
console.log(secondColor); // 'green'
const person = { name: '홍길동', age: 30 };
const { name, age } = person;

console.log(name); // 홍길동
console.log(age); // 30