본문 바로가기
언어/Javascript, Typescript

[js] 배열 합치기(concat(), spread 연산자, push())

by minhyeok.lee 2023. 4. 25.
반응형

Javascript에서 2개 이상의 배열을 하나의 배열로 만드는 3가지 방법

 

1. concat()을 이용한 배열 합치기
2. spread 연산자를 이용한 배열 합치기
3. push()를 이용한 배열 합치기

 


 

1. concat()을 이용한 배열 합치기

const arr1 = ['a', 'b', 'c'];
const arr2 = ['d', 'e', 'f'];
const arr3 = arr1.concat(arr2);
console.log(arr3);

 

출력값

['a', 'b', 'c', 'd', 'e', 'f']

 


 

2. Spread 연산자를 이용한 배열 합치기

const arr1 = ['a', 'b', 'c'];
const arr2 = ['d', 'e', 'f'];
const arr4 = [...arr1, ...arr2]
console.log(arr4);

 

출력값

['a', 'b', 'c', 'd', 'e', 'f']

 


 

3. push()를 이용한 배열 합치기

const arr1 = ['a', 'b', 'c'];
const arr2 = ['d', 'e', 'f'];

const arr6 = [];
arr6.push(...arr1);
arr6.push(...arr2); 
console.log(arr6);

 

출력값

['a', 'b', 'c', 'd', 'e', 'f']

 


 

※ 주의

 - spread 연산자를 사용하지 않으면 다음과 같이 배열안에 배열이 중첩된 구조로 들어간다.

const arr1 = ['a', 'b', 'c'];
const arr2 = ['d', 'e', 'f'];

const arr5 = [arr1, arr2]
console.log(arr5);

 

출력값

[ [ 'a', 'b', 'c' ], ['d', 'e', 'f']]

 

 

 - spread 연산자를 사용하지 않은 push() 예제

const arr1 = ['a', 'b', 'c'];
const arr2 = ['d', 'e', 'f'];

const arr7 = [];
arr7.push(arr1);
arr7.push(arr2); 

console.log(arr7);

 

출력값

[ [ 'a', 'b', 'c' ], ['d', 'e', 'f']]
반응형

댓글