slice

Tags
자르기
새로운 배열 생성
요약
얕은복제 후 원하는 위치의 요소만 잘라냄 / 원본 배열은 바뀌지 않음.
 
arr.slice([begin[, end]])
  • 얕은 복사 후, 원하는 부분만 잘라서 반환.
    • begin부터 end-1까지 잘라냄.
  • end가 생략되면 배열의 끝까지(arr.length) 추출합니다.
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant']; console.log(animals.slice(2)); // 2번째 인덱스부터 끝까지 자름 // ["camel", "duck", "elephant"] console.log(animals.slice(2, 4)); //2~3번째 인덱스만 추출 // ["camel", "duck"] console.log(animals.slice(1, 5)); // 1~4번쨰 인덱스만 추출 // ["bison", "camel", "duck", "elephant"] console.log(animals.slice(1,-1)); // 1번째 인덱스부터 마지막-1 요소까지 잘라냄 // ['bison', 'camel', 'duck'] console.log(animals.slice(-2)); // 끝에서 두번째요소부터 끝까지 자름 // ['duck', 'elephant'] console.log(animals.slice(1)); // 맨앞 요소 하나만 제거하고 싶은 경우, like shift() // ['bison', 'camel', 'duck', 'elephant']