계발하는 개발자

[JS] 배열의 특정 부분 자르는 방법 | slice 메서드 본문

📌 Language/Javascript

[JS] 배열의 특정 부분 자르는 방법 | slice 메서드

dev_genie 2023. 11. 21. 00:27

slice()

주어진 배열의 begin부터 end까지(end 미포함)를 새로운 배열 객체로 반환하는 메서드

원본 배열은 바뀌지 않는다.

 

Array.prototype.slice() - JavaScript | MDN

slice() 메서드는 어떤 배열의 begin 부터 end 까지(end 미포함)에 대한 얕은 복사본을 새로운 배열 객체로 반환합니다. 원본 배열은 바뀌지 않습니다.

developer.mozilla.org

 

기본 구조

    표시된 것은 optional 이며, 필요할 때 선택해서 사용하면 된다.

arr.slice([begin, end])

 

begin

잘라낼 배열의 시작 인덱스

 

end 

잘라낼 배열의 종료 인덱스 (미포함)

end index가 생략되면, begin index부터 배열의 끝까지 잘라낸다.

array.slice(1, 3)와 같이 end index를 설정하는 경우, 이는 1~3 요소까지를 가져오는 게 아니라,

인덱스 3 이전까지의 요소를 가져오게 된다.

 

사용법

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

animals.slice(2);
// ["camel", "duck", "elephant"]

animals.slice(2, 4);
// ["camel", "duck"]

animals.slice();
// ["ant", "bison", "camel", "duck", "elephant"]

animals.slice(2, -1);
// ["camel", "duck"]
LIST
profile

dev_genie

@dev_genie

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!