slice() 메서드는 어떤 배열의 시작 위치부터 끝 위치까지(끝 위치의 값은 미포함) 값을 복사하여 새로운 배열을 반환한다.
원본 배열은 바뀌지 않음.
문법은 아래와 같다.
arr.slice([begin[, end]])
mdn에서 가져온 사용 예시는 아래와 같다.
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2));
// 1. 결과: Array ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4));
// 2. 결과: Array ["camel", "duck"]
console.log(animals.slice(1, 5));
// 3. 결과: Array ["bison", "camel", "duck", "elephant"]
console.log(animals.slice(-2));
// 4. 결과: Array ["duck", "elephant"]
console.log(animals.slice(2, -1));
// 5. 결과: Array ["camel", "duck"]
console.log(animals.slice());
// 6. 결과: Array ["ant", "bison", "camel", "duck", "elephant"]
하나씩 살펴보자면
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2));
// 1. 결과: Array ["camel", "duck", "elephant"]
1번과 같이 시작 위치만 입력한 경우, 해당 위치부터 배열 끝까지 포함된 배열을 출력한다.
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2, 4));
// 2. 결과: Array ["camel", "duck"]
2번은, 시작위치와 끝위치를 모두 입력한 경우다. 끝위치의 값은 배열에 포함되지 않는 다는 점을 주의해야 한다.
따라서 index 2와 3의 값을 포함한 배열이 출력됐다.
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(1, 5));
// 3. 결과: Array ["bison", "camel", "duck", "elephant"]
3번은 index 1부터 5의 앞까지의 값들을 포함하므로, index 1부터 4까지의 값을 포함한 배열을 출력한다.
끝 위치 값이 포함되지 않기 때문에 끝 위치를 입력하면서 배열 끝까지 포함하고 싶은 경우 마지막 index + 1 을 끝위치로 입력해야 함을 기억하자.
array.length를 끝위치로 활용한 경우라고도 볼 수 있겠다.
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(-2));
// 4. 결과: Array ["duck", "elephant"]
4번의 경우 시작 위치를 음수로 입력했는데, 음수인 경우 마지막 값의 index를 -1로 여겨 하나 씩 앞으로 올수록 index에 -1을 해나간다.
뒤에서 2번째 값이 시작 위치이므로, 뒤에서 2번째부터 마지막값까지 포함된 배열을 출력한다.
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2, -1));
// 5. 결과: Array ["camel", "duck"]
5번은 index 2를 시작위치, -1을 끝 위치로 입력했다. 끝 위치의 값은 포함되지 않기 때문에, index 2부터 뒤에서 2번째 (-2) 값이 포함된 배열이 출력됐다.
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice());
// 6. 결과: Array ["ant", "bison", "camel", "duck", "elephant"]
마지막으로 6번처럼 아무 인자도 입력하지 않으면, 전체 배열을 그대로 출력한다.
이름이 비슷한 splice()는 기존 배열을 수정하며 요소를 추가하거나 삭제하는 메서드이므로 주의하자.
[js 메서드] 배열.splice()
JavaScript에서 splice() 메서드는 배열의 요소를 추가하거나 제거하는 메서드입니다. splice() 메서드는 배열을 변경합니다. 즉, 원래 배열을 수정합니다. splice() 메서드는 원래 배열에서 시작 인덱스
walwaldev.tistory.com
공식 문서: https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
Array.prototype.slice() - JavaScript | MDN
slice() 메서드는 어떤 배열의 begin 부터 end 까지(end 미포함)에 대한 얕은 복사본을 새로운 배열 객체로 반환합니다. 원본 배열은 바뀌지 않습니다.
developer.mozilla.org
'Node.js > JavaScript' 카테고리의 다른 글
[js 메서드] 배열.sort() (0) | 2023.06.16 |
---|---|
[js 메서드] 배열.reduce() (0) | 2023.06.16 |
[JS문법] ...(three dots, 점 세개)의 사용법 두 가지(객체/배열 vs 함수) (0) | 2023.05.10 |
[개념 정리] 단축평가(short circuit evaluation) - &&, || (0) | 2023.04.19 |
[node.js 메서드] 스트링으로 묶인 배열을 배열로 바꾸기 (0) | 2023.04.05 |