slice() 메서드

solie·2021년 9월 2일
0
const alphabet ['a', 'b', 'c', 'd', 'e'];

console.log(alphabet.slice(2));
// expected output : ['c', 'd', 'e'];

console.log(alphabet.slice(2, 4));
//expected output : ['c', 'd'];

console.log(alphabet.slice(1, 5));
//expected output : ['b', 'c', 'd', 'e'];

console.log(alphabet.slice(-2));
//expected output : ['d', 'e']

console.log(alphabet.slice(2, -1));
//expected output : ['c', 'd']

문법

Array.slice([begin[, end]])

매개변수
begin : 0을 시작으로 하는 시작점에 대한 인덱스를 의미

이때 음수 인덱스는 배열의 끝자리에서 부터의 '길이'를 나타낸다
-> .slice(-2)는 배열에서 마지막 두 개의 엘리먼트를 추출한다.

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

end : 추출할 마지막 대상의 엘리먼트에 대한 인덱스를 의미. ' slice 는 end 인덱스를 "제외"하고 추출한다' => 예를 들면, slice(1, 4)는 두번째 요소부터 네번째 요소까지 추출한다.(즉 배열이 [ 1, 2, 3, 4, 5, 6, ...] 일때 2, 3 및 4 를 추출)

-- end가 생략되면 slice()는 배열의 끝까지 추출한다.
-- end의 값이 배열의 길이보다 크다면, slice()는 배열의 끝까지 추출한다.

예제)

// slice를 사용하여 myCar 에서 newCar 라는 새 배열을 만든다.
let myVolvo = { color: 'black' , wheels: 4, engine: { cylinders: 4, size:2.2 }}
let myCar = [myVolvo, 2, 'cherry condition', 'purchased 2021']
let newCar = myCar.slice(0,2)

console.log('myCar = ' + JSON.stringify(myCar))
// expected output : myCar = [{color: 'black', wheels: 4, engine: { cylinders: 4, size: 2.2}, 2, 'cherry 

condition', 'purshased 2021']
console.log('newCar = ' + JSON.stringify(newCar))
// expected output : newCar = [{color: 'black', wheels: 4, engine: { cylinders: 4, size: 2.2}, 2]

console.log('myCar[0].color = ' + myCar[0].color)
// expected output : myCar[0].color = black

console.log('newCar[0].color = ' + newCar[0].color)
// expected output : newCar[0].color = black

myVolvo.color = 'blue'

console.log('The new color of my Volve is ' + myVolvo.color)
// expected output : The new color of my Volve is blue

console.log('myCar[0].color = ' + myCar[0].color)
// expected output : myCar[0].color = blue

console.log('newCar[0].color = ' + newCar[0].color)
// expected output : newCar[0].color = blue

참조

profile
2개월차 FE지망

0개의 댓글