Javascript의 배열관련 method 중 slice와 splice가 있습니다.

헷갈리기 쉬운 두 method에 대해 정확히 알아보고자 합니다.

 

- 정의 및 차이-

MDN에 기재된 각 method의 정의는 하기와 같습니다.

 

Array.prototype.slice()

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.

 

Array.prototype.splice()

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. 

 

정의로부터 알아본 차이는 하기와 같습니다.

 

slice는,

1. 원본 배열을 수정하지 않습니다.

2. parameter로 지정한 범위를 shallow copy 한 새 배열을 반환합니다.

 

splice는,

1. 원본 배열을 수정합니다.

2. 요소의 삭제, 대체, 추가가 가능합니다.

(slice는 삭제만 가능)

 

 

- 문법 - 

slice는 하기 문법을 통해 사용합니다. 

 

slice()

→ 기존 배열을 shallow copy한 새로운 배열을 반환합니다. 
slice(start)

→ start index부터 끝까지 요소를 새로운 배열로 반환합니다.
slice(start, end)

start index부터 end index 까지의 요소를 새로운 배열로 반환합니다.

 

 

splice는 하기 문법을 통해 사용합니다. 

 

splice(start)

원본 배열의 start index 이후의 요소들을 모두 제거합니다. 
splice(start, deleteCount)

원본 배열의 start index부터 deleteCount만큼의 요소들을 제거합니다. 
splice(start, deleteCount, item1)

원본 배열의 start index부터 deleteCount만큼의 요소들을 제거하고 item1을 삽입합니다.
splice(start, deleteCount, item1, item2, itemN)

원본 배열의 start index부터 deleteCount만큼의 요소들을 제거하고 item들을 삽입합니다.

 

parameter를 비교하니 두 method의 차이가 명확히 다가옵니다.

slice는 삭제, splice는 삭제를 포함한 수정으로 기억하면 좋을 듯 합니다.

 

 

- 사용 예시 - 

상기 내용을 참고하여 하기 예제를 작성합니다.

const fruits = ['🥝''🍅''🍒''🍌''🥭''🍍''🍋'];
const newFruits1 = fruits.slice(2);
const newFruits2 = fruits.slice(24);
 
console.log('newFruits1', newFruits1);
console.log('newFruits2', newFruits2);
 
// animal1~animal4는 동일한 배열임
const animals1 = ['🦁''🐷''🐔''🐲'];
animals1.splice(1);
console.log('spliced animals1', animals1);
 
const animals2 = ['🦁''🐷''🐔''🐲'];
animals2.splice(11);
console.log('spliced animals2', animals2);
 
const animals3 = ['🦁''🐷''🐔''🐲'];
animals3.splice(21'🦊');
console.log('spliced animals3', animals3);
 
const animals4 = ['🦁''🐷''🐔''🐲'];
animals4.splice(21'🦊''🐨');
console.log('spliced animals4', animals4);
cs

 

터미널에 하기와 같은 결과가 출력됩니다.

 

 

 

+ Recent posts