Array에 쓸 수 있는 유용한 함수 "splice"
5780 단어 JavaScriptJavaScript
Array.prototype.splice()
- mdn 정의
" The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place"
=> splice()는 배열의 콘텐츠를 바꿀 때 사용하는 메서드인데 배열의 기존 element를 제거하거나 새로운 element로 교체해줌으로써 배열의 콘텐츠를 바꿔준다고 한다.
언제 사용하면 될까?
- 배열의 특정 인덱스를 시작으로 원하는 갯수의 element를 제거하고싶을 때 (배열의 특정 element 제거)
- 배열의 특정 인덱스 뒤의 모든 element를 제거하고 싶을 때
- 배열의 특정 element를 제거하고 새로운 element로 교체하고 싶을 때
Syntax
splice(start) //(시작인덱스)
splice(start, deleteCount) //(시작인덱스,제거할 갯수)
splice(start, deleteCount, item1) //(시작인덱스,제거할 갯수,그뒤 추가할 요소)
splice(start, deleteCount, item1, item2, itemN) //(시작인덱스,제거할 갯수,그뒤 추가할 요소...)
- start
배열에서 바꾸고자하는 element의 인덱스 - deleteCount (optional)
start지점부터 제거할 갯수 - item1, item2, ... (optional)
start지점에서 시작해 배열에 추가할 element들
📌예
let shoppingList = ['📗','🥕','⚽','👠','⌚'];
//Q.쇼핑리스트에서 당근을 제거하고 싶다면?
const carrotIdx = shoppingList.indexOf('🥕');
shoppingList.splice(carrotIdx,1);
console.log(shoppingList);//output : ['📗', '⚽', '👠', '⌚']
//Q.쇼핑리스트에서 구두와 시계를 제거하고 농구공과 야구공을 추가하고 싶다면?
const shoesIdx = shoppingList.indexOf('👠');
shoppingList.splice(shoesIdx,2,'🏀','⚾');
console.log(shoppingList);//output: ['📗', '⚽', '🏀', '⚾']
//Q.축구공 포함 그 뒤 담긴 아이템을 모두 제거하고 싶다면?
const soccerballIdx = shoppingList.indexOf('⚽');
shoppingList.splice(soccerballIdx);
console.log(shoppingList); //output: ['📗']
참고
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
Author And Source
이 문제에 관하여(Array에 쓸 수 있는 유용한 함수 "splice"), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@yebb/JavaScript-Array에-쓸-수-있는-유용한-함수-splice저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)