[TIL] slice vs splice

JIEUN YANG·2023년 2월 16일
0

When a delete Button is clicked, clicked data should be removed on page.
In that perspective, There are two way to get rid of clicked data
One is slice method, and the other is splice method.

Both are used with array data structure and return array as well.
On the other hand, It's necessary to know some differences.


slice

slice() slice elements from start index to right before end one and return sliced arrays from original array.

slice(start, end)

const sliceTest = [1,2,3,4,5]
slice(0, 3) // [1,2,3] slice from index 0 to index 2 (doesn't contain end index)

console.log(sliceTest) // [1,2,3,4,5] ** no change in original array 

splice

splice() splice elements from start index and remove as much as given count and return spliced arrays from original array.

splice(start, deleteCount)

const spliceTest = [1,2,3,4,5]
splice(0, 3) // [1,2,3,4] remove 3 elements from starting index
console.log(spliceTest) // [5] ** change in original array 
profile
violet's development note

0개의 댓글