Programming/JavaScript
JavaScript - 배열 요소 제거하기
besforyou999
2023. 6. 7. 14:46
자바스크립트 배열의 요소 제거하는 법을 알아보자.
1. delete 연산자
자바스크립트 배열은 객체이기 때문에 배열의 특정 요소는 프로퍼티이다.
그러므로 delete 연산자를 이용해 배열의 특정 요소를 삭제할 수 있다.
1
2
3
4
5
6
7
|
const arr = [1, 2, 3];
delete arr[1];
console.log(arr); // [ 1, <1 empty item>, 3 ]
console.log(arr.length); // 3
|
cs |
하지만 length에 변화를 주지는 못한다. 즉, 희소배열이 된다.
2. splice
희소배열을 만들지 않고 특정 요소만을 제거한 배열을 만들고 싶은 경우 활용하면 좋은 메소드
1
2
3
4
5
6
7
|
const arr = [1, 2, 3];
arr.splice(1, 1);
console.log(arr); // [1, 3]
console.log(arr.length); // 2
|
cs |