Javascript의 슬라이스 방법 이해

안녕하세요 👋, 이전 게시물에서 방법을 설명했습니다.
여기서는 몇 가지 예를 들어 슬라이스 방법을 설명하겠습니다.
이름에는 큰 차이가 없지만(추가 p만 추가) 메커니즘이나 작동 방식이 많이 다릅니다.

Slice method does not mutate the original array.


  • 네, 제대로 읽으셨습니다. splice 방식과 달리 슬라이스 방식은 원래 배열의 내용을 변경하지 않습니다.
  • 오히려 원래 배열의 세그먼트/분수/조각의 복사본을 반환합니다(보다 정확하게는 a shallow copy ).

  • 구문을 살펴보십시오.

    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];
    


  • 위의 예에서 원래 배열과 결과 배열이 정확히 동일한지 궁금할 수 있습니다. 그렇다면 여기에서 슬라이스 방법을 사용하는 것은 도대체 무엇입니까?
  • 원래 배열의 복사본( shallow copy )을 반환합니다.
  • 다음 코드 블록에서 설명합니다.

  • 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];
    


  • 위의 예에서 슬라이스 방법은 지정된 인덱스로 시작하여 배열의 끝까지 슬라이스 또는 배열 부분을 제공합니다.
  • 더 멋진 것은 없지만 start가 +ve , -ve , 0 및 범위를 벗어난 인덱스가 될 수 있는 몇 가지 사용 사례가 있습니다.
  • 하나씩 살펴보겠습니다.

  • 예 - 3




    let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    let resultedArray = numbers.slice(-2);
    console.log(' result - 1 ', resultedArray);   // [8, 9];
    


  • 시작이 -ve 정수로 지정되면 배열의 끝에서 가리키고 슬라이스/는 끝까지 배열의 일부를 제공합니다.

  • 예 - 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];
    


  • 시작이 0인 경우. 단순히 복사본을 만듭니다.

  • 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];
    


  • 위의 예에서 슬라이스 방법은 시작 인덱스 - 2에서 끝 인덱스까지 배열의 일부를 제공하지만 끝 인덱스에 있는 요소는 제외합니다
  • .
  • 따라서 인덱스 2와 3에서 각각 요소 3과 4를 얻습니다(인덱스 4에 있는 요소를 얻지 못했습니다).

  • When the end is specified then element at that position is excluded in the resulting array after slice


  • 이제 다른 사용 사례는 end can -ve가 될 수 있습니다. 위의 예를 살펴본 경우 아이디어를 얻었을 수 있으므로 자세한 내용은 다루지 않겠습니다.

  • 예 - 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];
    


  • 들러주셔서 감사합니다!. 유용하다고 생각되면 공유를 고려하십시오. 여기에서 나와 연결할 수 있습니다.
  • 좋은 웹페이지 즐겨찾기