본문 바로가기
2022년

Array Method : Splice vs Slice

by 박상윤 2021. 7. 15.

Splice()

기존 요소를 제거하거나 교체하고 새 요소를 추가하여 배열의 내용을 변경해준다.

 

매개변수

splice(start, deleteCount, item1, item2, itemN)

 

반환값

삭제된 요소를 포함하는 배열

한 요소만 제거되면 한 요소의 배열이 반환

요소가 제거되지 않으면 빈 배열이 반환

 

start : 배열 변경을 시작할 인덱스

deleteCount : 제거할 배열의 요소 수를 나타내는 정수

item1,item2,... : 배열에 추가할 요소

 

let number = [1,2,3,4,5,6];
let remove = number.splice(1,0,3);

//number = [3,1,2,3,4,5,6]
//remove = []

추가적 예시 : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

 

Array.prototype.splice() - JavaScript | MDN

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. To access part of an array without modifying it, see slice().

developer.mozilla.org

 

Slice()

원래 배열을 변경하지 않는다. 원래 배열에서 요소의 얕은 복사본을 반환한다.

 

매개변수

slice(start,end)

start: 추출을 시작할 0부터 시작하는 인덱스

end : 0부터 시작해서 추출을 종료하기 전을 나타내는 인덱스, end드는 추출할 인덱스로 포함되지 않는다.

ex) slice(1,4) -> 2번째 요소 ~ 4번째 요소까지 추출 (요소 index 1,2,3)

 

반환값

추출된 요소를 포함하는 새 배열

 

let fruits = ['Apple','Banana','Orange','Lemon'];
let citrus = fruits.slice(1,3)

// fruits contains ['Apple','Banana','Orange','Lemon'];
// citrus contains ['Banana','Orange']

추가적 예시 : 

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

 

Array.prototype.slice() - JavaScript | MDN

The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.

developer.mozilla.org

 

'2022년' 카테고리의 다른 글

TP: BCSD - Account&Calendar / 2021-07-16  (0) 2021.07.16
Array.from()  (0) 2021.07.16
Parameter vs Argument  (0) 2021.07.15
최대 매출(Sliding Window)  (0) 2021.07.15
2021/07/14 - CodeReview  (0) 2021.07.14