본문 바로가기
Language/JavaScript

[JavaScript] concat() - 서로 다른 문자열 또는 배열 병합하기/합치기

by 썸머워즈 2021. 1. 5.
반응형

스크립트를 사용하는 중에 서로 다른 배열 또는 문자열을 합쳐야 하는 경우가 생길 수 있는데,

concat() 이라는 메서드에 대해 알아보고자 한다.

 

제목 그대로 문자열끼리 혹은 배열끼리 사용이 가능한 메서드이며

각각 String.prototype.concat() / Array.prototype.concat()을 의미한다.

 

▷ 구문

.concat(value1[, value2, value2, ..., valueN])

 

예제를 통해 알아보도록 하자.

 

▷ 예제1) String.prototype.concat()

var str1 = 'mine';
var str2 = 'it';
var str3 = 'record';

console.log(str1.concat(str2, str3));
// "mineitrecord"

console.log(str1.concat(' ', str2, ' ', str3));
// "mine it record"

 

구문과 마찬가지로 String.prototype.concat()은 기준 문자열 str1에 concat() 메서드 안에 있는 값들을 그대로 이어 붙인 결과를 반환하였다.

 

그래도 알아둬야 할 것은 concat() 메서드보다는 할당 연산자 (+, +=) 를 사용하는게 성능상 몇 배 더 빠르다는 결과가 있다.

 

참고 : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String/concat

 

String.prototype.concat() - JavaScript | MDN

concat() 메서드는 매개변수로 전달된 모든 문자열을 호출 문자열에 붙인 새로운 문자열을 반환합니다.

developer.mozilla.org

 

▷ 예제2) Array.prototype.concat()

var mine = [0, 1, 2];
var it = [3, 4, 5];
var record = [6, 7, 8];

console.log(mine.concat(it, record));
// [0, 1, 2, 3, 4, 5, 6, 7, 8]

 

Array.prototype.concat() 메서드 역시 기준 배열에 concat() 메서드 안에 있는 배열들을 그대로 이어 붙은 결과를 반환하는 것이다.

 

Array.prototype.concat()에는 하나 알아둬야할 것이 있는데 얕은 복사 기능이 존재한다는 것이다.

보통 A라는 변수에 담긴 배열을 B라는 변수에 담으면 둘이 연결되어 있는 상태로 존재하는데 그걸 방지하기 위해 얕은 복사를 많이 사용한다.

 

참조 : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/concat

 

Array.prototype.concat() - JavaScript | MDN

concat() 메서드는 인자로 주어진 배열이나 값들을 기존 배열에 합쳐서 새 배열을 반환합니다.

developer.mozilla.org

반응형


댓글

TOP