JavaScript slice와 splice의 차이점

성태팍·2024년 11월 19일
post-thumbnail

초심찾기 운동의 일환으로 프로그래머스에서 코테 문제를 몇개 씩 풀고 있다.

배열을 다룰 때 자주 사용하는 함수 중에 slice와 splice가 있는데 두 함수가 맨날 헷갈린다.
이번 포스팅에서는 두 메서드의 차이점과 사용 예제를 통해 각각의 특징을 알아보겠다.

1. slice()

slice 메서드는 배열의 일부를 선택하여 새로운 배열을 반환한다. 원본 배열은 수정되지 않는다.

특징

  • 원본 배열을 변경하지 않음 (비파괴적 메서드)
  • 새로운 배열을 반환한다.
  • 시작 인덱스부터 끝 인덱스 이전까지 선택한다

구문

array.slice(startIndex, endIndex);
  • 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']

2. splice()

splice 메서드는 배열의 내용을 추가, 제거, 또는 교체할 수 있다. 원본 배열이 변경된다.

특징

  • 원본 배열을 변경 (파괴적 메서드)
  • 제거된 요소들을 배열로 반환한다.
  • 추가 및 제거를 동시에 수행할 수 있다.

구문

array.splice(startIndex, deleteCount, item1, item2, ...);
  • 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']

3. slice와 splice의 주요 차이점 비교

특징slicesplice
원본 배열 변경 여부변경하지 않음 (비파괴적)변경함 (파괴적)
반환 값추출된 새로운 배열제거된 요소들의 배열
주요 기능배열의 일부를 복사배열 요소 제거, 추가, 또는 교체
인자 설명startIndex, endIndex (끝은 포함되지 않음)startIndex, deleteCount, 추가할 요소들

결국은 원본 배열 유지, 일부 요소만 가져오고 싶어 -> slice 사용
배열 내용 직접 수정해야 해 -> splice 사용

이젠 안 헷갈리겠지

profile
안녕하세요. 반갑습니다. 건강하세요.

0개의 댓글