programming/javascript

shift, splice, slice 함수 사용법 정리

worldint 2023. 4. 8. 21:54

.shift()

shift는 배열의 첫변째 요소를 제거하고 제거된 요소를 반환함

arr.shift()를 하면 

arr[0]을 반환하고 arr에서 arr[0]제거됨

var myFish = ["angel", "clown", "mandarin", "surgeon"];

console.log("myFish before: " + myFish);
// myFish before: [angel, clown, mandarin, surgeon ]

var shifted = myFish.shift();

console.log("myFish after: " + myFish);
// myFish after: [ clown, mandarin, surgeon ]

console.log("Removed this element: " + shifted);
// Removed this element: angel

 

splice()

기존 배열의 요소를 삭제하거나 교체해서 배열을 변경하며

제거된 요소가 담긴 새 배열을 리턴한다.

배열을 비워줄때 splice(0)이런식으로 써줄수도 있다.

0번째 배열부터 제거하라는 의미이기 때문에

// 요일이 담긴 배열 생성하기 
let months = ["January", "February", "Monday", "Tuesday"];
let days = months.splice(2); // 인덱스 2부터 배열 변경

console.log(days); // ["Monday", "Tuesday"]
console.log(months); //["January", "February"]

.splice(2,1)이런식으로 두번째 파라미터를 넣어주면 인덱스2부터 1개의 요소를 제거하라는 뜻

splice(2,2,'hi','bye')이렇게 3번째 파라미터 부터는 새롭게 넣어줄 요소를 써주면 그게 들어간다

let months = ["January", "February", "Monday", "Tuesday"];
let days = months.splice(2,2,'hi','bye'); // 인덱스 2부터 배열 변경

console.log(days); // ["Monday", "Tuesday"]
console.log(months); // ["Monday", "Tuesday","hi","bye"]

arr.splice(2,0,"hi")

두번째 매개변수를 0으로 하면 아무것도 제거하지 않고 arr[2] 부분에 "hi"를 끼워넣는다

 

 

slice()

slice() 메서드는 어떤 배열의 begin 부터 end 까지(end 미포함)에 대한 얕은 복사본을 새로운 배열 객체로 반환합니다. 원본 배열은 바뀌지 않습니다.

slice(begin, end)

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

원본 배열은 바뀌지않음

slice(-1)이렇게하면 가장 뒤에 있는 요소가 반환됨