[JavaScript]
기초
- [JS] Js기초
- [JS] Js기초 변수
- [JS] Js기초 자료형
- [JS] Js기초 형변환
- [JS] Js기초 연산자
- [JS] Js기초 반복문
- [JS] Js기초 switch
- [JS] Js기초 function
- [JS] Js기초 객체
- [JS] Js기초 배열
중급
- [JS] Js중급 호이스팅(Hoisting)과 TDZ(Temporal Dead Zone)
- [JS] Js중급 생성자함수
- [JS] 객체 메소드(Object methods), 계산된 프로퍼티(Computed property)
- [JS] 심볼(Symbol)
- [JS] WeakMap WeakSet
- [JS] 숫자, 수학 method (Number, Math)
- [JS] 문자열 메소드(String methods)
- [JS] 배열 메소드(Array methods)
- [JS] 구조 분해 할당 (Destructuring assignment)
- [JS] 매개변수 리스트와 전개 문법(Rest parameters and spread syntax)
- [JS] 클로저(Closure)
- [JS] setTimeout / setInterval
- [JS] call / apply / bind
- [JS] 상속, 프로토타입(Prototype)
- [JS] 클래스(Class)
- [JS] 클로미스(Promise)
- [JS] 비동기 처리(Async/Await)
- [JS] Generator
- [JS] 메모리 릭(Memory Leak)
배열(Array)을 배워보자! 데이터를 줄줄이 관리하는 초강력 무기야! 🚀
1. 배열 만들기
1
2
3
4
5
6
7
8
9
10
11
12
// 기본 배열 만들기
let fruits = ["🍎", "🍌", "🍊"];
let numbers = [1, 2, 3, 4, 5];
let mixed = ["안녕", 42, true, null, { name: "김코딩" }];
// 배열 길이 확인
console.log(fruits.length); // 3
// 배열 요소 접근
console.log(fruits[0]); // "🍎"
console.log(fruits[1]); // "🍌"
console.log(fruits[fruits.length - 1]); // "🍊" (마지막 요소)
2. 배열 메서드 (기본)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
let heroes = ["아이언맨", "토르", "스파이더맨"];
// 배열 끝에 추가/제거
heroes.push("닥터 스트레인지"); // 끝에 추가
console.log(heroes); // ["아이언맨", "토르", "스파이더맨", "닥터 스트레인지"]
heroes.pop(); // 끝에서 제거
console.log(heroes); // ["아이언맨", "토르", "스파이더맨"]
// 배열 앞에 추가/제거
heroes.unshift("캡틴 아메리카"); // 앞에 추가
heroes.shift(); // 앞에서 제거
// 중간에 추가/제거
heroes.splice(1, 1); // 1번 인덱스부터 1개 제거
heroes.splice(1, 0, "블랙 위도우"); // 1번 인덱스에 추가
3. 배열 탐색하기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
let numbers = [1, 2, 3, 4, 5];
// forEach: 각 요소 순회
numbers.forEach((num, index) => {
console.log(`${index}번째: ${num}`);
});
// map: 새로운 배열 만들기
let doubled = numbers.map((num) => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
// filter: 조건에 맞는 요소만 선택
let evenNumbers = numbers.filter((num) => num % 2 === 0);
console.log(evenNumbers); // [2, 4]
// find: 조건에 맞는 첫 번째 요소 찾기
let firstBigNumber = numbers.find((num) => num > 3);
console.log(firstBigNumber); // 4
4. 배열 정렬과 변환
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
let fruits = ["바나나", "사과", "오렌지"];
// 정렬하기
fruits.sort(); // 알파벳 순으로 정렬
console.log(fruits); // ["바나나", "사과", "오렌지"]
// 뒤집기
fruits.reverse();
console.log(fruits); // ["오렌지", "사과", "바나나"]
// 문자열로 합치기
let fruitString = fruits.join(", ");
console.log(fruitString); // "오렌지, 사과, 바나나"
// 문자열을 배열로 나누기
let sentence = "안녕,나는,코딩해";
let words = sentence.split(",");
console.log(words); // ["안녕", "나는", "코딩해"]
5. 실전 예제: 게임 인벤토리!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class GameInventory {
constructor() {
this.items = [];
}
addItem(item) {
this.items.push(item);
console.log(`${item.name} 획득! 🎁`);
}
removeItem(itemName) {
const index = this.items.findIndex((item) => item.name === itemName);
if (index !== -1) {
const removed = this.items.splice(index, 1)[0];
console.log(`${removed.name} 제거! 🗑️`);
}
}
showItems() {
console.log("🎒 인벤토리 목록:");
this.items.forEach((item, index) => {
console.log(`${index + 1}. ${item.name} (${item.type})`);
});
}
sortByType() {
this.items.sort((a, b) => a.type.localeCompare(b.type));
console.log("아이템을 종류별로 정렬했어요! ✨");
}
}
// 사용 예시
const inventory = new GameInventory();
inventory.addItem({ name: "불꽃검", type: "무기" });
inventory.addItem({ name: "힐링포션", type: "소비" });
inventory.addItem({ name: "방패", type: "방어구" });
inventory.showItems();
inventory.sortByType();
inventory.showItems();
6. 모던 자바스크립트의 꿀팁! 🍯
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 1. 구조 분해 할당
const [first, second, ...rest] = [1, 2, 3, 4, 5];
console.log(first); // 1
console.log(rest); // [3, 4, 5]
// 2. 스프레드 연산자
const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = [...arr1, ...arr2];
console.log(combined); // [1, 2, 3, 4]
// 3. 배열 비구조화
function printScores([first, second, third]) {
console.log(`1등: ${first}점`);
console.log(`2등: ${second}점`);
console.log(`3등: ${third}점`);
}
printScores([98, 95, 88]);
7. 실용적인 배열 메서드들!
1
2
3
4
5
6
7
8
9
10
11
12
// reduce: 배열을 하나의 값으로 줄이기
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((total, num) => total + num, 0);
console.log(`총합: ${sum}`); // 15
// some: 조건을 만족하는 요소가 하나라도 있는지
const hasEven = numbers.some((num) => num % 2 === 0);
console.log(`짝수가 있나요? ${hasEven}`); // true
// every: 모든 요소가 조건을 만족하는지
const allPositive = numbers.every((num) => num > 0);
console.log(`모두 양수인가요? ${allPositive}`); // true
이제 배열은 완전 마스터! 데이터 관리가 한결 쉬워졌지? 😎