slice() & splice()

Daniel·2023년 7월 18일
0

Front-End

목록 보기
13/14

두 함수 모두 배열에서 요소를 추출하거나 배열을 변경하는데 사용된다.

두 함수의 목적이나 사용법에 대해 알아보자

// Example array
const fruits = ['apple', 'banana', 'orange', 'mango', 'kiwi'];

// Using slice()
const slicedFruits = fruits.slice(1, 4);
console.log(slicedFruits);
// Output: ['banana', 'orange', 'mango']
console.log(fruits);
// Output: ['apple', 'banana', 'orange', 'mango', 'kiwi']

// Using splice()
const splicedFruits = fruits.splice(1, 3);
console.log(splicedFruits);
// Output: ['banana', 'orange', 'mango']
console.log(fruits);
// Output: ['apple', 'kiwi']

.slice()

장점

  • 원본 배열을 수정하지 않는다. -> 얕은복사 수행
  • 새배열을 반환한다.
  • 배열에서 요소의 하위 집합을 추출하는데 사용

단점

  • 새 배열을 반환할때 추가 메모리 사용

.splice()

장점

  • 원본배열을 직접 수정
  • 배열에서 요소를 제거, 교체 및 삽입할 수 있다.
  • 제거된 요소를 직접 반환하지 않는다.

단점

  • 원본 배열을 직접적으로 수정하므로 코드에 영향이 있을 수 있다.
  • 제거된 요소를 직접 반환하지 않는다. -> void
profile
응애 나 애기 개발자

1개의 댓글

comment-user-thumbnail
2023년 7월 18일

글이 많은 도움이 되었습니다, 감사합니다.

답글 달기