Javascript의 슬라이스 방법 이해
여기서는 몇 가지 예를 들어 슬라이스 방법을 설명하겠습니다.
이름에는 큰 차이가 없지만(추가 p만 추가) 메커니즘이나 작동 방식이 많이 다릅니다.
Slice method does not mutate the original array.
구문을 살펴보십시오.
slice(start, end)
참고: 시작과 끝은 모두 선택 사항일 수 있습니다.
이제 이것을 세 부분으로 나눌 수 있습니다.
하나씩 살펴보겠습니다.
slice()
예 - 1
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let resultedArray = numbers.slice();
console.log(' result - 1 ', resultedArray); // [1, 2, 3, 4, 5, 6, 7, 8, 9];
let products = [ { id : 100 , productName : 'Mobile', manufacturer : { id : 1 , countryCode : 'USA'}} ,{ id : 101 , productName : 'TV'}, { id : 102 , productName : 'Washing Machine', manufacturer : { id : 2 , countryCode : 'CAN'}} ];
let resultedArray = products.slice();
console.log( ' products ', products);
console.log( ' resultedArray ', resultedArray);
// To check their equality
console.log( ' Equality ', products === resultedArray ) // false
// To check the equality of child nodes ( nested keys )
console.log(' child node ', products[0].manufacturer === resultedArray[0].manufacturer ); // true
That means slice method does make a shallow copy.
slice(start)
예 - 2
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let resultedArray = numbers.slice(2);
console.log(' result - 1 ', resultedArray); // [3, 4, 5, 6, 7, 8, 9];
예 - 3
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let resultedArray = numbers.slice(-2);
console.log(' result - 1 ', resultedArray); // [8, 9];
예 - 4
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let resultedArray = numbers.slice(0);
console.log(' result - 1 ', resultedArray); // [1, 2, 3, 4, 5, 6, 7, 8, 9];
slice() <=> slice(0)
예 - 5
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let resultedArray = numbers.slice(20);
console.log(' result - 1 ', resultedArray); // [];
slice(start, end)
예 - 6
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let resultedArray = numbers.slice(2, 4);
console.log(' result - 1 ', resultedArray); // [3, 4];
When the end is specified then element at that position is excluded in the resulting array after slice
예 - 7
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let resultedArray = numbers.slice(2, -4);
console.log(' result - 1 ', resultedArray); // [3, 4, 5];
Reference
이 문제에 관하여(Javascript의 슬라이스 방법 이해), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/swasdev4511/understanding-slice-method-in-javascript-24di텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)