배열은 여러 개의 값을 순차적으로 나열한 자료 구조이다.
const arr = ['바나나', '복숭아', '키위'];const arr2 = new Array();
const arr3 = new Array(10);
const arr4 = new Array(1, 2, 3);const arr5 = Array.of(10);
const arr6 = Array.of(1, 2, 3);
const arr7 = Array.of("hello", "js");const arr = ['바나나', '복숭아', '키위'];
console.log(arr[0]); // 바나나
console.log(arr[1]); // 복숭아
console.log(arr[2]); // 키위
length배열에 담긴 요소의 개수를 확인할 수 있다.
const arr = ['바나나', '복숭아', '키위'];
console.log(arr.length); // 3
배열에 요소를 추가하거나 삭제하면 자동으로 갱신 된다.
push배열의 가장 뒷 부분에 요소를 추가할 때 사용한다.
배열.push(요소)의 형태로 사용한다.
const arr = ['바나나', '복숭아', '키위'];
arr.push('딸기');
console.log(arr); // ['바나나', '복숭아', '키위', '딸기']
pop배열의 가장 뒷 부분의 요소를 제거할 때 사용한다.
배열.pop()의 형태로 사용한다.
const arr = ['바나나', '복숭아', '키위', '딸기'];
arr.pop();
console.log(arr); // ['바나나', '복숭아', '키위']
unshift배열의 맨 앞에 요소를 추가한다.
배열.unshift(요소)의 형태로 사용한다.
const fruits = ['바나나', '오렌지'];
fruits.unshift('사과');
console.log(fruits); // ['사과', '바나나', '오렌지']
shift배열의 맨 앞 요소를 제거 후 반환한다.
const fruits = ['사과', '바나나', '오렌지'];
console.log(fruits.shift()); // 사과
console.log(fruits); // ['바나나', '오렌지']
slice배열.slice(인덱스, 제거할요소개수)의 형태로 사용한다.
배열의 index 위치에 있는 요소를 선택해 잘라낸다.
const animals = ['고양이', '강아지', '토끼', '햄스터', '거북이'];
const removed = animals.slice(1, 2);
console.log(removed); // ['강아지']
console.log(animals); // ['고양이', '강아지', '토끼', '햄스터', '거북이']
splice배열.splice(인덱스, 제거할요소개수, 추가할 요소)의 형태로 사용한다.
배열의 index 위치에 있는 요소를 선택해 제거하고 요소를 추가한다.
const animals = ['고양이', '강아지', '토끼', '햄스터', '거북이'];
animals.splice(2, 1, '새우');
console.log(animals); // ['고양이', '강아지', '새우', '햄스터', '거북이']
indexOf배열에서 요소가 위치한 index를 리턴 한다.
없는 요소를 요청할 경우 -1이 나온다.
const colors = ['빨강', '파랑', '노랑', '초록', '파랑'];
console.log(colors.indexOf('파랑')); // 1
console.log(colors.indexOf('보라')); // -1
특정 인덱스부터 검색하는 것도 가능하다
const colors = ['빨강', '파랑', '노랑', '초록', '파랑'];
console.log(colors.indexOf('파랑', 2)); // 4
lastIndexOf배열의 요소가 위치한 마지막 index를 리턴 한다.
const colors = ['빨강', '파랑', '노랑', '초록', '파랑'];
console.log(colors.lastIndexOf('파랑')); // 4
includes배열에 해당 요소가 존재 하는지 여부를 boolean 타입으로 리턴 한다.
const colors = ['빨강', '파랑', '노랑', '초록', '파랑'];
console.log(colors.includes('노랑')); // true
console.log(colors.includes('보라')); // false
concat두 개 이상의 배열을 결합 한다.
const fruits1 = ['사과', '바나나'];
const fruits2 = ['오렌지', '포도'];
const allFruits = fruits1.concat(fruits2);
console.log(allFruits); // ['사과', '바나나', '오렌지', '포도']
join배열을 구분자로 결합해 문자열로 반환한다.
const fruits = ['사과', '바나나', '오렌지', '포도'];
console.log(fruits.join()); // 사과,바나나,오렌지,포도
console.log(fruits.join(' ')); // 사과 바나나 오렌지 포도
console.log(fruits.join('-')); // 사과-바나나-오렌지-포도
reverse배열의 순서를 뒤집는다.
const numbers = [1, 2, 3, 4, 5];
numbers.reverse();
console.log(numbers); // [5, 4, 3, 2, 1]
sort배열을 기준에 따라 정렬한다.
오름차순 정렬이 기본이며, 정렬 후 정렬 순서를 유지한다.
기본적으로 문자열 정렬이 된다.
오름차순 / 내림차순 정렬할 때에는 다른 방식으로 전달해야 한다.
- 오름차순 : numbers.sort((a, b) ⇒ a -b)
- 내림차순 : numbers.sort((a, b) ⇒ b - a)
const numbers = [10, 5, 40, 25, 1000, 1];
numbers.sort();
console.log(numbers); // [1, 10, 1000, 25, 40, 5]
forEach배열의 각 요소를 반복하며 모든 요소에 대해 콜백 함수를 호출한다.
arr.forEach(callback(item[, index[, array]])) 형태로 사용한다.
- item : 처리할 배열의 요소
- index : 처리할 배열 요소의 인덱스
- array : forEach를 호출한 배열
const fruits = ['사과', '바나나', '오렌지'];
fruits.forEach(fruit => {
console.log(fruit);
});
map
각 요소를 변환 해서 새로운 배열을 만드는 메서드이다.
forEach의 동작 원리와 같지만 forEach와는 다르게 새로운 배열을 반환 한다.
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
콜백 함수란 (Callback function)
다른 함수에 인자로 전달되는 함수이다.
외부 함수 내에 호출되어 특정 작업을 진행 한다.
function sayHello() {
console.log('안녕하세요!');
}
function sayBye() {
console.log('안녕히가세요!');
}
function greet(callback) {
console.log('인사를 시작합니다.');
callback();
console.log('인사가 끝났습니다.');
}
greet(sayHello);
filter조건에 맞는 요소로만 구성된 새로운 배열을 반환한다.
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // [2, 4, 6, 8, 10]
reduce배열에 콜백 함수를 실행해 누적된 하나의 결과 값을 반환한다.
array.reduce(<콜백 함수>, <초기값>);
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 15
some조건을 만족하는 요소가 하나라도 있으면 true를 반환한다.
boolean 타입의 값만 반환 한다.
const numbers = [1, 3, 5, 7, 8];
const hasEven = numbers.some(num => num % 2 === 0);
console.log(hasEven); // true
every배열의 모든 요소가 조건을 만족 하면 true를 반환한다.
하나라도 통과하지 못 하면 false를 반환 후 중지한다.
boolean 타입의 값만 반환한다.
빈 배열은 항상 true를 반환한다.
const numbers = [1, 3, 5, 7, 9];
const allPositive = numbers.every(num => num > 0);
console.log(allPositive); // true
find조건을 만족하는 첫 번째 요소를 반환 후 중지한다.
const numbers = [1, 3, 5, 8, 9, 12];
const firstEven = numbers.find(num => num % 2 === 0);
console.log(firstEven); // 8
findIndex조건을 만족하는 첫 번째 요소의 인덱스를 반환 후 중지한다.
찾는 요소가 없으면 -1을 반환한다.
const numbers = [1, 3, 5, 8, 9, 12];
const firstEvenIndex = numbers.findIndex(num => num % 2 === 0);
console.log(firstEvenIndex); // 3