slice와 splice의 차이점

Date:     Updated:

카테고리:

태그:

📌 글의 목적: slice와 splice 메서드의 차이점에 대해서 다른 사람들에게 정보를 제공하기 위해 작성한 글

slice 메서드와 splice 메서드 모두, 첫 번째 파라미터start로 잘라낼 인덱스의 시작점을 의미한다.

slice(begin, end);
slice(start: 추출을 시작할 인덱스, end: 추출을 끝낼 인덱스);

splice(start, deleteCount);
splice(start: 자르기 시작할 인덱스, deleteCount: start부터  개를 삭제할 것인지에 대한 );

위의 코드와 같이 splice 메서드deleteCount 파라미터는 start부터 n 개를 삭제하겠다는 값을 의미한다. slice 메서드end 파라미터는 지정된 인덱스를 포함하지 않고 지정한 end의 앞에서 추출을 끝낸다.

const numberList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

let sliceResult = numberList.slice(3, 4 + 1);

let spliceResult = numArray.splice(3, 4);

console.log(sliceResult); // [3, 4]
console.log(spliceResult); // [3, 4, 5, 6]

slice 메서드원본 배열을 변형시키지 않는다.

const array = [1, 2, 3, 4, 5];

const result = array.slice(2, 5); //outcome = (3) [3, 4, 5]

const result2 = array.slice(-2); //output == [4, 5]

console.log(array); //outcome = (5) [1, 2, 3, 4, 5]

위의 코드와 같이 array의 값인 배열은 변형되지 않았다.

slice 메서드와는 달리 splice원본 배열을 변형시킨다.

const fruits = ["🍎", "🍌", "🍓", "🍑", "🍋"];

console.log(fruits.splice(1, 1)); // [ '🍌' ]

console.log(fruits); // ['🍎', '🍓', '🍑', '🍋']

위의 코드와 같이 원본 배열인 fruits를 살펴보면 🍌가 삭제되어 원본 배열이 변형된 것을 볼 수 있다.

그리고 splice 메서드는 원본 배열의 value를 삭제하고 데이터를 새롭게 추가할 수 있다.

const fruits = ["🍎", "🍌", "🍓", "🍑", "🍋"];

fruits.splice(1, 1, "🍏", "🍉");

console.log(fruits); // ['🍎', '🍏', '🍉', '🍓', '🍑', '🍋']

위의 코드를 살펴보면, splice(1, 1)를 통해서 🍌를 삭제하고, 그 이후에 🍏, 🍉은 삭제한 value의 자리에 추가된 것을 확인할 수 있다.

💡 MDN: Array.prototype.splice()

💡 MDN: Array.prototype.slice()

댓글남기기