배열?
비원시타입 자료형으로, 여러개의 값을 순차적으로 담을 수 있다.
🔎 배열의 특징
1. 배열의 요소에는 0부터 시작하는 숫자(index)가 매겨져 있다.
2. 배열의 요소는 어떤 형태여도 무관하다
1. 배열 생성
배열 생성자와 배열 리터럴을 통해 생성할 수 있다
→ 배열 리터럴이 간편해 주로 쓰인다.
예시
let arr1 = new Array();//배열 생성자
let arr2 = [];//배열 리터럴
2. 배열 요소 조작 메서드
2- 1. 배열의 요소 추가
| 배열 메서드 | 설명 |
| push | 배열의 맨 뒤에 새로운 요소를 추가하는 메서드 |
| unshift | 배열의 맨 앞에 새로운 요소를 추가하는 메서드 |
예시
let arr = [3,4]
arr.push(5,6,7) //뒤에 추가
arr.unshift(0,1,2)//앞에 추가
console.log(arr)//[0,1,2,3,4,5,6,7]
2- 2. 배열 요소 삭제
| 배열 메서드 | 설명 |
| pop | 배열의 맨 뒤의 요소를 제거하고 반환하는 메서드 |
| shift | 배열의 맨 앞의 요소를 제거하고 반환하는 메서드 |
| splice | 배열의 특정부분을 제거하고 반환하는 메서드 |
예시
let fruits = [apple, banana, cherry, durian, eggplant]
fruits.pop();// eggplant
console.log(fruits)//[apple, banana,cherry,durian]
fruits.shift();//apple
console.log(fruits)//[banana,cherry,durian,eggplant]
📖 splice
arr.splice(startIndex, deleteCount )
→ arr의 startIndex번째 요소부터 deleteCount의 개수만큼 삭제한 배열을 반환한다.
let colors = ['purple', 'skyblue', 'green', 'yellow', 'orange'];
colors.splice(1, 3);//[skyblue, green, yellow]
console.log(colors); //[purple,orange]
🔎 pop, push / shift,unshift의 차이
shift와 unshift는 push, pop보다 동작이 느리다
→ 배열의 맨 앞의 요소를 추가, 삭제를 하면서 기존의 인덱스에 영향을 주기 때문에 느려진다.
출처
효빈 - 한 방으로 끝내는 자바스크립트 강의
Mordern Javascript Tutorial - https://ko.javascript.info/
Mdn web Docs -https://developer.mozilla.org/ko/