반응형
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']]
반응형
'언어 > Javascript, Typescript' 카테고리의 다른 글
[js, Next.js] <input> 한글 입력 후 엔터 시 중복 이벤트 발생 문제 (0) | 2023.04.27 |
---|---|
[js] JSON관련 메소드(JSON.stringify(), JSON.parse()) (0) | 2023.04.26 |
[js] 소수점 특정 자리수까지 표시하기 (0) | 2023.04.24 |
[js] 옵셔널 체이닝(optional chaining)_'?.' (0) | 2023.04.18 |
[js, ts] 정규식을 이용하여 공백, 전화번호에서의 -, 특수문자 제거 함수 (0) | 2023.04.07 |
댓글