01
배열 조작 메서드
1. push
배열의 맨 뒤에 요소를 추가합니다.
const arr = [1, 2, 3];
arr.push(4);
console.log(arr);
// 출력결과: [1, 2, 3, 4]
2. pop
배열의 마지막 요소를 제거하고 반환합니다.
const arr = [1, 2, 3];
const removed = arr.pop();
console.log(arr);
console.log(removed);
// 출력결과: [1, 2]
// 출력결과: 3
3. shift
배열의 첫 번째 요소를 제거하고 반환합니다.
shift는 원본 배열을 변경하므로, 성능이 중요한 경우 빈번히 사용하지 않는 것을 권장합니다.
const arr = [1, 2, 3];
const removed = arr.shift();
console.log(arr);
console.log(removed);
// 출력결과: [2, 3]
// 출력결과: 1
4. unshift
배열의 맨 앞에 요소를 추가합니다.
unshift는 배열의 모든 요소를 이동시키므로 성능에 영향을 줄 수 있습니다.
대신 push와 pop을 사용하는 것을 더 권장합니다.
const arr = [2, 3];
arr.unshift(1);
console.log(arr);
// 출력결과: [1, 2, 3]
02
배열 메서드: 원본 배열을 건드리지 않음
1. slice
배열의 특정 구간을 잘라내서 새로운 배열로 반환합니다. 원본 배열은 변경되지 않습니다.
const arr = [1, 2, 3, 4];
const sliced = arr.slice(1, 3);
console.log(arr);
console.log(sliced);
// 출력결과: [1, 2, 3, 4]
// 출력결과: [2, 3]
2. concat
두 개의 배열을 합쳐서 새로운 배열을 반환합니다.
const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = arr1.concat(arr2);
console.log(arr1);
console.log(combined);
// 출력결과: [1, 2]
// 출력결과: [1, 2, 3, 4]
03
배열 탐색 메서드
1. includes
배열에 특정 요소가 포함되어 있는지 확인합니다.
const arr = [1, 2, 3];
console.log(arr.includes(2));
console.log(arr.includes(4));
// 출력결과: true
// 출력결과: false
단, 배열을 직접 비교할 때는 순서와 요소가 모두 일치해야 true를 반환합니다.
const arr1 = [1, 2, 3];
const arr2 = [3, 2, 1];
console.log(arr1.includes(arr2));
// false (배열 순서가 다르기 때문에)
2. indexOf
특정 요소의 인덱스를 반환합니다. 요소가 없으면 -1을 반환합니다.
예를 들어, 배열에서 특정 값을 찾을 때 해당 값이 첫 번째 요소이면 0,
두 번째 요소이면 1을 반환합니다. 요소가 없으면 -1을 반환합니다.
const arr = [1, 2, 3];
console.log(arr.indexOf(2)); // 2는 배열의 두 번째 요소이므로 인덱스 1 반환
console.log(arr.indexOf(1)); // 1은 배열의 첫 번째 요소이므로 인덱스 0 반환
console.log(arr.indexOf(4)); // 4는 배열에 없으므로 -1 반환
// 출력결과: 1
// 출력결과: 0
// 출력결과: -1
3. findIndex
조건을 만족하는 첫 번째 요소의 인덱스를 반환합니다.
const arr = [{ id: 1 }, { id: 2 }, { id: 3 }];
const index = arr.findIndex((item) => item.id === 2);
console.log(index);
// 출력결과: 1
4. find
조건을 만족하는 첫 번째 요소 자체를 반환합니다.
findIndex는 조건을 만족하는 요소의 위치(인덱스)를 반환하고, find는 조건을 만족하는 요소 자체를 반환합니다.
예를 들어, findIndex는 숫자를 반환하지만 find는 객체나 배열 등 요소 자체를 반환한다는 차이가 있습니다.
const arr = [{ id: 1 }, { id: 2 }, { id: 3 }];
const item = arr.find((item) => item.id === 2);
console.log(item);
// 출력결과: { id: 2 }
5. forEach
배열의 각 요소를 순차적으로 처리하는 메서드인데,
배열을 변경하거나 새로운 값을 반환하는 게 아니라 단순히 반복 작업을 할 때 사용합니다.
반환값은 없고, 배열을 변경하지 않으며, 단지 순차적으로 모든 요소를 처리합니다.
const arr = [1, 2, 3, 4];
arr.forEach((item) => console.log(item));
// 출력:
// 1
// 2
// 3
// 4
6. some
배열의 요소 중 하나라도 주어진 조건을 만족하면 true를 반환하고,
모든 요소가 조건을 만족하지 않으면 false를 반환합니다.
const arr = [1, 2, 3, 4];
const hasEven = arr.some((item) => item % 2 === 0);
console.log(hasEven);
// 출력결과: true (배열 내에 짝수인 2와 4가 있기 때문에)
some 메서드는 배열끼리 비교할 때는 순서가 필요 없다는 점이 중요합니다.
const arr1 = [1, 2, 3];
const arr2 = [3, 1, 2];
const result = arr1.some((item) => arr2.includes(item));
console.log(result);
// 출력결과: true (arr1의 1, 2, 3 중 하나라도 arr2에 포함되면 true 반환, 순서는 중요하지 않음)
04
배열 변환 메서드
1. filter
조건을 만족하는 요소들로 이루어진 새로운 배열을 반환합니다.
// 예제 1
const arr = [1, 2, 3, 4];
const filtered = arr.filter((item) => item > 2);
console.log(filtered);
// 출력결과: [3, 4]
// 예제 2: 짝수만 필터링
const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter((num) => num % 2 === 0);
console.log(evenNumbers);
// 출력결과: [2, 4, 6]
// 예제 3: 문자열 길이 조건 필터링
const words = ["short", "medium", "very long word"];
const longWords = words.filter((word) => word.length > 5);
console.log(longWords);
// 출력결과: ["medium", "very long word"]
2. map
배열의 각 요소에 콜백 함수를 실행한 결과를 모아 새로운 배열을 반환합니다.
// 예제 1
const arr = [1, 2, 3];
const mapped = arr.map((item) => item * 2);
console.log(mapped);
// 출력결과: [2, 4, 6]
// 예제 2: 문자열 배열의 길이 계산
const words = ["apple", "banana", "cherry"];
const lengths = words.map((word) => word.length);
console.log(lengths);
// 출력결과: [5, 6, 6]
// 예제 3: 객체 배열에서 특정 속성 추출
const users = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 35 }
];
const names = users.map((user) => user.name);
console.log(names);
// 출력결과: ["Alice", "Bob", "Charlie"]
배열 정렬 메서드
1. sort
배열을 정렬합니다. 기본적으로는 문자열 순서로 정렬되므로 숫자 정렬 시 주의가 필요합니다.
const arr = [3, 1, 4, 2];
// 오름차순 정렬
arr.sort((a, b) => a - b);
console.log(arr);
// 출력결과: [1, 2, 3, 4]
// 내림차순 정렬
arr.sort((a, b) => b - a);
console.log(arr);
// 출력결과: [4, 3, 2, 1]
// 문자열 배열 정렬 예시
const arr = ["banana", "Apple", "orange", "apple"];
// 기본 정렬 (대소문자 구분)
arr.sort();
console.log(arr);
// 출력결과: ["Apple", "apple", "banana", "orange"]
// 대소문자 구분으로 'A' < 'a' 이기 때문에 "Apple"이 먼저 나옵니다.
// 대소문자 구분 없이 정렬하려면 toLowerCase() 사용
arr.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
console.log(arr);
// 출력결과: ["Apple", "apple", "banana", "orange"]
// 대소문자 구분 없이 알파벳 순서대로 정렬됩니다.
const arr = [
{ name: "banana", type: "fruit" },
{ name: "Apple", type: "fruit" },
{ name: "orange", type: "fruit" },
{ name: "grape", type: "fruit" }
];
// `name` 속성 값을 기준으로 정렬 (대소문자 구분)
arr.sort((a, b) => a.name.localeCompare(b.name));
console.log(arr);
// 출력결과: [
// { name: "Apple", type: "fruit" },
// { name: "banana", type: "fruit" },
// { name: "grape", type: "fruit" },
// { name: "orange", type: "fruit" }
// ]
// 대소문자 구분 없이 정렬하려면 `toLowerCase()` 사용
arr.sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()));
console.log(arr);
// 출력결과: [
// { name: "Apple", type: "fruit" },
// { name: "banana", type: "fruit" },
// { name: "grape", type: "fruit" },
// { name: "orange", type: "fruit" }
// ]
2. toSorted
정렬된 새로운 배열을 반환합니다. 원본 배열은 변경되지 않습니다.
const arr = [3, 1, 4, 2];
const sorted = arr.toSorted((a, b) => a - b);
console.log(arr);
console.log(sorted);
// 출력결과: [3, 1, 4, 2]
// 출력결과: [1, 2, 3, 4]
배열을 문자열로 변환
1. join
배열의 모든 요소를 하나의 문자열로 합쳐 반환합니다.
const arr = ["JavaScript", "is", "fun"];
const str = arr.join(" ");
console.log(str);
// 출력결과: "JavaScript is fun"
const str2 = arr.join("-");
console.log(str2);
// 출력결과: "JavaScript-is-fun"
문자열 메서드
1. toLowerCase
문자열을 모두 소문자로 변환하여 반환합니다.
const str = "JavaScript Is Fun";
const lowerStr = str.toLowerCase();
console.log(lowerStr);
// 출력결과: "javascript is fun"
2. toUpperCase
문자열을 모두 대문자로 변환하여 반환합니다.
const str = "JavaScript is fun";
const upperStr = str.toUpperCase();
console.log(upperStr);
// 출력결과: "JAVASCRIPT IS FUN"
Date 객체 사용법
1. new Date()로 생성
Date 객체를 생성하여 현재 시간 또는 특정 시간을 나타냅니다.
const now = new Date();
console.log(now);
// 출력결과: 2025-01-22T14:25:31.814Z
2. getTime()으로 타임스탬프 추출
타임스탬프는 1970년 1월 1일부터 경과한 밀리초를 나타냅니다.
이 값은 전 세계에서 동일하게 사용됩니다.
const now = new Date();
const timestamp = now.getTime();
console.log(timestamp);
// 출력결과: 1737555945194
3. 날짜.시간 세분화 추출
Date 객체에서 연도, 월, 일, 시, 분, 초를 추출할 수 있습니다.
const now = new Date();
const year = now.getFullYear(); // 연도
const month = now.getMonth() + 1; // 월 (0부터 시작하므로 +1)
const date = now.getDate(); // 일
const hours = now.getHours(); // 시
const minutes = now.getMinutes(); // 분
const seconds = now.getSeconds(); // 초
console.log(`${year}-${month}-${date} ${hours}:${minutes}:${seconds}`);
// 출력결과: '2025-1-22 14:25:31'
4. toLocaleString
Date 객체를 사용자가 설정한 지역 시간 문자열로 변환합니다.
const now = new Date();
const localString = now.toLocaleString();
console.log(localString);
// 출력결과: 1/22/2025, 2:44:47 PM
const localString2 = now.toLocaleString("ko-KR");
console.log(localString2);
// 출력결과: 2025. 1. 22. 오후 2:44:47
'DEVELOPMENT > JavaScript' 카테고리의 다른 글
[JS] 콜백 (Callback) (0) | 2025.02.20 |
---|---|
[JS] 동기와 비동기, 둘이 싸우면 누가 이길까? (5) | 2025.01.23 |
[JS] 정규표현식 (RegExp) (4) | 2024.06.21 |
[JS] let,const 와 var (3) | 2024.05.22 |
[JS] Todo-List (2) | 2024.05.13 |