본문 바로가기
공부일지/Javascript

splice() 메서드

by 곰인간 2023. 5. 9.

splice() 메서드는 배열의 기존 요소를 삭제 또는 교체 하거나

새 요소를 추가하여 배열의 내용을 변경합니다.
(삭제한 요소들은 배열로 반환된다.)


*참고자료 : MDN - splice()

array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

splice 메서드의 구문을 확인해보면 

start, deleteCount, items로 이루어져 있다.

start : 원본 배열의 요소를 제거하기 시작할 인덱스이고, start만 지정하면 원본 배열의 start부터 모든 요소를 제거한다.
start가 음수인 경우 배열의 끝에서의 인덱스를 나타낸다.
만약에 start가 -1(음수)이면 마지막 요소를 가리키고 -n이면 마지막에 n번째 요소를 가리킨다.

deleteCount : 원본 배열의 요소를 제거하기 시작할 인덱스인 start부터 제거할 요소의 개수이다.
(deleteCount를 생략하면 start부터 끝까지 다 제거한다.
deleteCount가 배열.length - start 보다 크면 start부터 끝까지 다 제거한다.)
deleteCount가 0인 경우에는 아무런 요소도 제거되지 않는다.

items : 제거한 위치에 삽입할 요소들의 목록이다.
생략할 경우 원본 배열에서 요소들을 제거하기만 한다.


const animal = ['bear', 'dog', 'cat', 'tiger', 'lion']
const result = animal.splice(1, 2, 'rabbit', 'raccoon')

console.log(animal)
console.log(result)

예제를 준비했다.

animal이라는 배열에 splice메서드를 이용해서 반환값을 result라는 변수에 할당하였다.

console.log(animal)을 찍어보면.

[ 'bear', 'rabbit', 'raccoon', 'tiger', 'lion']

이러한 결과값이 나오고,

console.log(result)는

['dog', 'cat']

이라는 결과값이 나온다.


다음 예제를 살펴보자.

const animal = ['bear', 'dog', 'cat', 'tiger', 'lion']
const result = animal.splice(1, 0, 'rabbit', 'raccoon')

console.log(animal)
console.log(result)

위 예제는

splice메서드를 이용해서 

첫 번째 인수 1은 삭제할 원본 배열의 인덱스의 위치를 나타내고,

deleteCount는 0개의 요소를 제거한다.
(deleteCount가 0이면 아무런 요소도 제거하지 않는다.)

그리고 그 자리에 새로운 요소인 'rabbit', 'raccoon'을 추가한다.

그러므로 console.log(animal) 결과값은

['bear', 'rabbit', 'raccoon', 'dog', 'cat', 'tiger', 'lion']
인덱스 1번 자리에 'rabbit'이 들어가고 다음 자리에 'raccoon'이 들어갔다.

console.log(result)는

[]
빈배열이 호출 된다.

삭제된 요소가 없으므로 빈 배열이 반환되었다.


이번 예제는 start와 deleteCount는 입력하지만 item값은 입력하지 않을 예정이다.

 

const animal = ['bear', 'dog', 'cat', 'tiger', 'lion']
const result = animal.splice(1, 2)

console.log(animal)
console.log(result)

위에 설명했지만,

start의 인수 1은 원본 배열의 인덱스의 위치,

deleteCount의 인수 2는 원본 배열의 인덱스의 위치이다.

원본 배열에서 1~2까지의 인덱스를 제거하는 코드이다.

확인해보자.

cosole.log(animal)

['bear', 'dog', 'cat', 'tiger', 'lion']에서

'dog', 'cat'이 제거된

['bear', 'tiger', 'lion']

라는 값이 출력된다.

console.log(result)는

['dog', 'cat']

제거된 요소인 'dog', 'cat'을 배열로 반환한다.


이번 예제는 start만 입력할 예정이다.

const animal = ['bear', 'dog', 'cat', 'tiger', 'lion']
const result = animal.splice(2)

console.log(animal)
console.log(result)

start의 인수 2는 원본 배열의 위치를 나타낸다.

그렇다면 위의 코드에서 cat이 될 것이고,

start값만 입력하면 cat부터 lion까지 삭제 될 것이다.

console.log(animal)을 찍어보면

['bear', 'dog']

로 원본 배열이 변경되고,

console.log(result)는

['cat', 'tiger', 'lion']

위 배열이 반환된다.


음수인 경우를 살펴보자.

이번엔 예제 두개를 준비했다.

const animal = ['bear', 'dog', 'cat', 'tiger', 'lion']
const result = animal.splice(-1)

console.log(animal)
console.log(result)

start가 -1인 예제이다.

위의 설명대로라면 start가 -1이면 배열의 마지막 부분이 제거 되어야한다.

console.log(animal)을 찍어서 확인해보자.

['bear', 'dog', 'cat', 'tiger']

콘솔로그를 찍어보면 배열의 마지막 인덱스인 'lion'이 삭제되었다.

console.log(result)를 호출하면,

['lion'] 

삭제된 'lion'은 result에 반환되어서 출력된다.

const animal = ['bear', 'dog', 'cat', 'tiger', 'lion']
const result = animal.splice(-3)

console.log(animal)
console.log(result)

이번엔 start에 -3을 입력하면

마지막 배열에서 3번째 요소까지 제거해야한다.

console.log(animal)을 찍어보면

['baer', 'dog']

위 배열이 출력되고

console.log(result)를 찍어보면

['cat', 'tiger', 'lion']

이라는 배열이 출력된다.


indexOf메서드를 사용해서 특정 요소의 인덱스를 취한 다음에

splice메서드를 사용하면 배열에서 특정 요소를 제거 할 수 있다.

const animal = ['bear', 'dog', 'cat', 'tiger', 'lion']
const index = animal.indexOf('lion')

if(index !== -1) {
	const remove = animal.splice(index, 1)
    console.log(`삭제된 아이템은? ${remove}`)
}

console.log(aniaml)

위 코드에서 삭제된 아이템인 remove를 콘솔에 찍어보면

indexOf메서드에 취한 'lion'인 것을 알 수 있다.

그리고 animal 배열을 확인해보면

['bear', 'dog', 'cat', 'tiger']

'lion'이 제거 되었다.

 

/*

indexOf메서드에서 배열 내에서 찾는 인덱스가 없으면 -1을 반환한다.

이러한 특성을 이용해서 if조건문의 조건으로 index !== -1을 입력하였다.

start에는 indexOf메서드로 찾은 'lion'이 index의 변수로 저장되어있다.

animal.splice(index, 1)은 결국에는

 index의 위치에 있는 요소 1개를 제거하는 것 이다.

*/


 

filter() 메서드를 이용해도 특정 요소가 제거 가능하다.
(중복된 경우에도 모두 제거된다.)

하지만 filter메서드를 이용한 경우는 다음에 알아보자.

splice메서드가 필요치 않으니.

댓글