splice() 메서드는 원본 배열
의 요소를 삭제 또는 교체하거나 새 요소를 추가하여 배열의 내용을 변경합니다.
// remove
const array = ['fist', 'second', 'third', 'fifth'];
const remove = array.splice(3, 1);
console.log(remove); // 'fifth'
console.log(array); // ['fist', 'second', 'third']
// add
cosnt add = array.splice(3,0,"fifth");
console.log(add); // []
console.log(array); // ['fist', 'second', 'third', 'fifth']
// replace
const replace = array.splice(3,0,'forth');
console.log(replace); // []
console.log(array); // ['fist', 'second', 'third', 'forth']
splice(start)
splice(start, deleteCount)
splice(start, deleteCount, item1)
splice(start, deleteCount, item1, item2, itemN)
start
배열의 변경할 인덱스를 의미한다.
만약, 배열의 길이보다 큰 값이 들어오면 start
는 배열의 길이로 설정된다.
음수로 설정하면 배열의 끝에서부터 설정된다.(-1,-2, ...-n)
deleteCount
(option)
제거할 요소의 수를 의미한다.
생략하거나 값이 (배열의 길이-start)보다 크면 start
부터 모든 요소가 제거된다.
item1, item2, ...itemN
(option)
배열에 추가할 요소를 의미하며, 지정하지 않으면 splice는 오로지 배열의 요소만 제거한다.
제거한 요소를 담은 배열을 반환한다.