0329 TIL : splice 메서드

Clear·2023년 3월 28일
0

Daily Posting

목록 보기
11/27

기본 사용법

array.splice(start, deleteCount, item1, item2, ...)
  • start: 배열 변경을 시작할 인덱스. 음수이면 배열의 끝에서부터 개수를 셉니다.
  • deleteCount: 삭제할 기존 배열 요소의 개수. 0으로 설정하면 요소가 제거되지 않습니다.
  • item1, item2 등: start 인덱스에서 시작하여 배열에 추가할 요소입니다.

사용 예시

  1. 배열에서 요소 제거
const fruits = ['apple', 'banana', 'cherry', 'date'];

// remove the second element
fruits.splice(1, 1);

console.log(fruits); // Output: ['apple', 'cherry', 'date']

// remove the last two elements
fruits.splice(-2);

console.log(fruits); // Output: ['apple']
  1. 배열에 요소 추가
const numbers = [1, 2, 3, 4];

// add two elements starting at index 2
numbers.splice(2, 0, 5, 6);

console.log(numbers); // Output: [1, 2, 5, 6, 3, 4]
  1. 배열의 요소 바꾸기
const colors = ['red', 'green', 'blue'];

// replace the second element
colors.splice(1, 1, 'yellow');

console.log(colors); // Output: ['red', 'yellow', 'blue']

요약

  • 3번째 인자가 없으면 삭제
  • 3번째 인자가 있으면, 교체 혹은 추가

0개의 댓글