
초심찾기 운동의 일환으로 프로그래머스에서 코테 문제를 몇개 씩 풀고 있다.
배열을 다룰 때 자주 사용하는 함수 중에 slice와 splice가 있는데 두 함수가 맨날 헷갈린다.
이번 포스팅에서는 두 메서드의 차이점과 사용 예제를 통해 각각의 특징을 알아보겠다.
slice 메서드는 배열의 일부를 선택하여 새로운 배열을 반환한다. 원본 배열은 수정되지 않는다.
array.slice(startIndex, endIndex);
const fruits = ['apple', 'banana', 'cherry', 'date'];
const sliced = fruits.slice(1, 3); // ['banana', 'cherry']
console.log(sliced); // ['banana', 'cherry']
console.log(fruits); // ['apple', 'banana', 'cherry', 'date']
splice 메서드는 배열의 내용을 추가, 제거, 또는 교체할 수 있다. 원본 배열이 변경된다.
array.splice(startIndex, deleteCount, item1, item2, ...);
const fruits = ['apple', 'banana', 'cherry', 'date'];
const removed = fruits.splice(1, 2); // ['banana', 'cherry']
console.log(removed); // ['banana', 'cherry']
console.log(fruits); // ['apple', 'date']
const fruits = ['apple', 'date'];
fruits.splice(1, 0, 'banana', 'cherry');
console.log(fruits); // ['apple', 'banana', 'cherry', 'date']
const fruits = ['apple', 'banana', 'cherry'];
fruits.splice(1, 1, 'grape');
console.log(fruits); // ['apple', 'grape', 'cherry']
| 특징 | slice | splice |
|---|---|---|
| 원본 배열 변경 여부 | 변경하지 않음 (비파괴적) | 변경함 (파괴적) |
| 반환 값 | 추출된 새로운 배열 | 제거된 요소들의 배열 |
| 주요 기능 | 배열의 일부를 복사 | 배열 요소 제거, 추가, 또는 교체 |
| 인자 설명 | startIndex, endIndex (끝은 포함되지 않음) | startIndex, deleteCount, 추가할 요소들 |
결국은 원본 배열 유지, 일부 요소만 가져오고 싶어 -> slice 사용
배열 내용 직접 수정해야 해 -> splice 사용
이젠 안 헷갈리겠지