728x90
반응형
const sliceArray = [1,2,3].slice(1,3)
두 개의 인자를 모두 선택적으로 활용하는데
첫번째 인자 undefined 시에 0으로 작동하고
두번째 인자 undefined 시에 배열의 길이로 작동한다!
정확하게는
첫번째 인자에 해당하는 인덱스부터
두번째 인자에 해당하는 인덱스 이전까지이다. (이 부분이 가끔 생소하게 다가온다 ㅎ)
여기서 slice()를 인자없이 쓸 수도 있는데 이 경우 결과값이 동일하여 무쓸모라 생각할 수 있는데
slice() 활용시 새로운 객체가 리턴되는 것이 핵심이기 때문에 복사 용도로 활용할 수 있다!
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]
console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]
p.s. 가장 정확하게 확인하는 방법은 역시나 mdn을 활용하는 방법!
developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
Array.prototype.slice() - JavaScript | MDN
The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.
developer.mozilla.org
반응형
'Googling > javascript' 카테고리의 다른 글
[JavaScript] 오픈소스 활용 json 엑셀파일로 내보내기 (feat. SheetJs) (0) | 2021.08.01 |
---|---|
[Javascript] Body에서 Drag & Drop 활용하기 (0) | 2021.05.12 |