[JS] 배열 추가 or 삭제

J.yeon·2024년 3월 27일

자주 사용되는 배열의 추가, 삭제 방법👏


배열 요소 추가

push()

배열 끝에 추가된다.

const array = [1, 2, 3];
array.push(4, 5);

console.log(array);
// [1, 2, 3, 4, 5]

unshift()

배열 맨 앞에 추가된다.

const array = [1, 2, 3];
array.unshift(4, 5);

console.log(array);
// [4, 5, 1, 2, 3]

splice()

첫 번째 인자: 시작(위치) 인덱스(index),
두 번째 인자: 삭제할 요소 갯수(0일시 삭제X),
세 번째 인자: 추가할 값

const array = [1, 2, 3];
array.splice(0,0, 7);

console.log(array);
// [7, 1, 2, 3]

*concat()

배열과 배열을 합쳐준다.

let array = [1, 2, 3];
let array2 = ['a', 'b', 'c'];

array.concat(array2);

console.log(array);
// [1, 2, 3, 'a', 'b', 'c']

*spread 연산자

배열, 문자열, 객체 등 반복 가능한 객체를 개별 분리, 나열해준다. (ES6)

push메소드 등 배열의 요소를 추가할 때, 분리된 배열끼리 합칠 경우 실수하는 부분이 있을 수 있다.

let array = [1, 2, 3];
let array2 = ['a', 'b', 'c'];

array.push(array2);

console.log(array);
// [1, 2, 3, [Array3]]

위처럼 배열 안에 배열로 들어가기 때문에 괄호를 벗겨주어야한다. 이때 spread 연산자(...)를 사용하면 편리하다.

let array = [1, 2, 3];
let array2 = ['a', 'b', 'c'];

array.push(...array2);

console.log(array);
// [1, 2, 3, 'a', 'b', 'c']


👇또는 아래처럼 원하는 위치에 추가 가능

let array = [1, 2, 3];
let array2 = ['a', 'b', ...array, 'c'];

console.log(array2);
// ['a', 'b', 1, 2, 3, 'c']



👇아래처럼도 가능

let array = [1, 2, 3];
let array2 = ['a', 'b', 'c'];

let total = [...array, ...array2];

console.log(total);
// [1, 2, 3, 'a', 'b', 'c']


배열 요소 삭제

pop()

배열 마지막 끝 요소를 제거한다.

const array = [1, 2, 3, 4];
array.pop();

console.log(array);
// [1, 2, 3]



👇삭제 값 반환 가능
const array = [1, 2, 3, 4];
const popped = array.pop();

console.log(popped);
// 4

shift()

배열 첫 번째 요소를 제거한다.

const array = [1, 2, 3, 4];
array.shift();

console.log(array);
// [2, 3, 4]



👇삭제 값 반환 가능
const array = [1, 2, 3, 4];
const shifted = array.shift();

console.log(shifted);
// 1

splice()

첫 번째 인자: 시작(위치) 인덱스(index),
두 번째 인자: 삭제할 요소 갯수(0일시 삭제X),
세 번째 인자: 추가할 값 (*삭제만 할거면 생략)

const array = [1, 2, 3, 4];
array.splice(1, 1);

console.log(array);
// [1, 3, 4]


const array = [1, 2, 3, 4];
array.splice(0, 2);

console.log(array);
// [3, 4]



👇삭제 값 반환 가능
const array = [1, 2, 3, 4];
const removed = array.splice(1, 2);

console.log(removed);
// [2, 3]

delete
만약 요소의 자리는 그대로 존재하되 값만 삭제하고 싶다면,

const array = [1, 2, 3, 4];
delete array[1];

console.log(array);
// [1, undefined, 3, 4]

profile
나혼자만 윈도우UP💻

0개의 댓글