Home [JavaScript] slice/splice 함수?
Post
Cancel

[JavaScript] slice/splice 함수?


slice() 함수란?

  • slice() 함수는 배열에서 원하는 범위를 복사한 새로운 배열 을 만든다.
  • 원본 배열이 그대로 보존되야 하는 상황에서 주로 사용한다.

배열에 0번쨰부터 2번쨰 index를 복사하는 코드

1
2
3
4
const array = ["a","b","c","d","e"];
const start = 0;
const last = 3;
console.log(array.slice(start,last));  //["a","b","c"]

start: 어디서 부터 자를지에 따른 시작점을 지정
last: 어디까지 자를지에 따른 맺음점을 지정

start 인자만 지정해줬을 때

  • 지정 순번부터 마지막까지 배열을 복사
1
2
const array = ["a","b","c","d","e"];
console.log(array.slice(3));  //["d","e"]

인자가 없을 떄

  • 처음부터 마지막까지 배열을 복사
1
2
const array = ["a","b","c","d","e"];
console.log(array.slice());  //["a","b","c","d","e"]

splice() 함수란?

  • splice() 함수는 배열에서 원하는 범위를 삭제하거나 새로운 값을 추가한다.
  • 원본 배열이 변경이 된다.
1
2
3
4
5
6
const array = ["a", "b", "c", "d", "e"];
const start = 1;
const num = 3;
const newArray = array.splice(start, num);
console.log(newArray)  // ["b","c","d"]
console.log(array);    // ["a","e"] 

기존 array변수에는 값이 사라졌고 그 값은 newArray에 담겼다.

start: 어디서 부터 자를지에 따른 시작점을 지정
num: start 앞에 몇개에 요소를 선택할지

삭제X 값추가

  • 2번쨰부터 아무값도 삭제하지 않고 값을 추가해보자
1
2
3
const array = ["a", "b", "c", "d", "e"];
array.splice(2,0,-1,-2)
console.log(array);  // ['a', 'b', -1, -2, 'c', 'd', 'e']

시작 인자와 마지막 인자 이후로는 그 자리에 추가해주고 싶은 값을 인자로 넘기게 된다.

삭제O 값추가

  • 원하는 값을 삭제하고 그 자리에 다른 값을 넣어보자
1
2
3
const array = ["a", "b", "c", "d", "e"];
array.splice(2,2,-1,-2,-3)
console.log(array);  // ['a', 'b', -1, -2, -3, 'e']

마치며

혹시 잘못된 정보나 궁금하신 게 있다면 편하게 댓글 달아주세요.
지적이나 피드백은 언제나 환영입니다.

This post is licensed under CC BY 4.0 by the author.