Javascript Array.prototype.slice()
Post

Javascript Array.prototype.slice()

slice() 메서드는 배열의 시작부터 끝까지의 얕은 복사본을 새로운 배열 객체로 반환한다.

원본배열에는 영향을 주지않는다.

arr.slice([begin[, end]]) 이처럼 사용하면된다.

매개변수 begin 자리는 0으로 시작하는 시작점에 대한 인덱스를 넣어주어야 한다.
음수 인덱스는 배열의 끝에서부터의 길이를 나타낸다.

begin이 undefined인 경우에는, 0번 인덱스부터 slice한다. begin이 배열의 길이보다 큰 경우에는, 빈 배열을 반환한다.

매개변수 end 자리는 추출을 종료할 0 기준의 인덱스이다.
slice는 end인덱스를 제외하고 추출한다.
예를 들어, slice(1,4)는 [0,1,2,3,4]일 경우 두번째 요소부터 네번째 요소인 [1,2,3]을 추출한다.

음수 인덱스는 배열의 끝에서부터의 길이를 나타낸다.

end가 생략되면 slice()는 배열의 끝까지(arr.length) 추출한다.

만약 end값이 배열의 길이보다 크면, slice()는 배열의 끝까지만 추출한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
    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"]

    console.log(animals.slice(-2));
    // Expected output: Array ["duck", "elephant"]

    console.log(animals.slice(2, -1));
    // Expected output: Array ["camel", "duck"]

    console.log(animals.slice());
    // Expected output: Array ["ant", "bison", "camel", "duck", "elephant"]

slice()메서드를 호출하여 배열형 객체와 콜렉션을 새로운 Array로 변환할 수 있다.

참고