splice() 메서드는 배열의 기존 요소를 삭제 또는 교체하거나 새 요소를 추가하여 배열의 내용을 변경 한다.
const months = ['Jan', 'March', 'April', 'June'];
// 1번 index에 'Feb' 값 추가
months.splice(1, 0, 'Feb');
console.log(months);
// 결과 값: Array ["Jan", "Feb", "March", "April", "June"]
const months = ["Jan", "Feb", "March", "April", "June"];
// 4번 index값을 삭제
months.splice(4, 1);
console.log(months);
// 결과 값: Array ["Jan", "Feb", "March", "April"]
const months = ["Jan", "Feb", "March", "April", "June"];
// 4번 index값을 'May'로 교체
months.splice(4, 1, 'May');
console.log(months);
// 결과 값: Array ["Jan", "Feb", "March", "April", "May"]
// 현재 배열은 0 ~ 4번 index까지 값이 있다.
const months = ["Jan", "Feb", "March", "April", "May"];
// 만약 현재 배열보다 긴 index를 교체하면, 교체할 값이 없기 때문에 값이 추가된다.
months.splice(5, 1, 'June');
console.log(months);
// 결과 값: Array ["Jan", "Feb", "March", "April", "May", "June"]
split() 메서드는 String
객체를 지정한 구분자를 이용하여 여러 개의 문자열로 나눠 준다.
const str = 'The quick brown fox jumps over the lazy dog.';
// 띄어쓰기 공백으로 구분해 준다.
const words = str.split(' ');
console.log(words);
// 결과 값: Array ["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog."]
console.log(words[3]);
// 결과 값: "fox"
// 공백 없이 구분하면 문자 원소 하나씩 구분된다.
const chars = str.split('');
console.log(chars[8]);
// 결과 값: "k"
// 인자값에 아무것도 입력하지 않으면 전체 문자열을 한 개의 원소로 가지는 배열이 생성된다.
const strCopy = str.split();
console.log(strCopy);
// 결과 값: Array ["The quick brown fox jumps over the lazy dog."]
slice() 메서드는 어떤 배열의 시작 부터 끝까지에 대한 얕은 복사본을 새로운 배열 객체로 반환한다.(원본 배열은 바뀌지 않는다.)
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2));
// 입력 된 인자 값 index의 원소부터 마지막 index 원소까지 출력 된다.
// 결과 값: Array ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4));
// 시작 index부터 끝 index의 전 index의 원소까지 출력 된다.
// 결과 값: Array ["camel", "duck"]
// 인자 값이 -인 경우는 뒤 index부터 시작된다.
console.log(animals.slice(-2));
// 뒤에서 2번째 원소부터 마지막 원소까지 출력 된다.
// 결과 값: Array ["duck", "elephant"]
console.log(animals.slice(2, -1)
// 2번째 index부터 -1번째 이전까지 즉, -2번 원소까지를 말한다.
// ['ant', 'bison', 'camel', 'duck', 'elephant'];
// 0 1 2 3 4
// -5 -4 -3 -2 -1
// 결과 값: Array ["camel", "duck"]
출처
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/slice