splice VS slice

김_리트리버·2020년 10월 5일
0

splice

기존 배열의 요소를 삭제, 수정하거나 새로운 요소를 기존배열에 삽입한다.

mutable 로 기존 배열이 수정된다.

array.splice('수정하고자 하는 index','삭제하고자 하는 요소 갯수',대체할 데이터 )

const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at index 1
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "June"]

months.splice(4, 1, 'May');
// replaces 1 element at index 4
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "May"]

slice

기존배열의 특정구간의 복사본 배열을 리턴한다.

array.slice('복사시작','복사끝') // 복사시작 이상 복사끝 미만 index 까지 복사

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
// 1 이상 5미만 
console.log(animals.slice(1, 5));
profile
web-developer

0개의 댓글