반응형
concat() 함수는 배열과 문자열에 사용이 가능하다.
이번 포스팅에선 문자열에 concat() 함수가 어떻게 사용 가능한지 알아보자.
const str = 'hello world';
console.log(str + 'abc'); // hello worldabc
console.log(str.concat('abc')); // hello worldabc
일반적으로 문자열 두 개를 더해서 문자열 합치는 것처럼 concat() 함수도 동일한 결과를 보인다.
const str = 'hello world';
console.log(str.concat('abc', '123', '456')); // hello worldabc123456
concatd() 함수는 두 개 이상의 문자열을 받을 수 있고 그 결과로 문자열 한 개로 합친다.
const str = 'hello world';
console.log(str.concat(' abc')); // hello world abc
console.log(str.concat(' ', 'abc')); // hello world abc
만약 문자열 여러 개를 합칠 때 합치는 문자열 사이마다 공백이 필요하면 위와 같은 방법으로 공백을 넣을 수 있다.
const str = 'hello world';
console.log(str.concat(1,2,3)); // hello world123
console.log(str.concat(true)); // hello worldtrue
console.log(str.concat(null)); // hello worldnull
console.log(str.concat(undefined)); // hello worldundefined
concat() 함수는 문자열뿐만 아니라 다른 데이터 타입도 받아들인다: (Number, Boolean, Null, Undefined, Array, Object).
합쳐진 데이터의 타입은 문자열이다.
const str = 'hello world';
console.log(str.concat([])); // hello world
console.log(str.concat([1,2,3])); // hello world1,2,3
console.log(str.concat(["1",2,3])); // hello world1,2,3
배열도 마찬가지로 받아들여진다.
특이점은 배열의 요소만 문자열에 합쳐지는 게 아니고, 요소 사이에 있는 콤마(,)도 합친 데이터에 포함된다.
const str = 'hello world';
console.log(str.concat({})); // hello world[object Object]
console.log(str.concat({name: 'john', age: 10})); // hello world[object Object]
객체도 받아들여지지만 합친 문자열에 [object Object]라고 나타나기 때문에 concat() 함수 사용에 객체를 넣는 것은 권하진 않는다.
반응형
'코딩 > Javascript' 카테고리의 다른 글
자바스크립트 - 배열의 각 요소의 인덱스와 요소를 새로운 배열에 출력하기 (entries() 함수) (0) | 2023.07.10 |
---|---|
자바스크립트 - 배열의 연속되는 요소들을 특정 인덱스에 복사하기 (copyWithin() 함수) (0) | 2023.07.07 |
자바스크립트 - 문자열 뒤에서부터 특정 문자를 검색하여 찾은 문자의 인덱스 찾기 (lastIndexOf() 함수) (0) | 2023.07.01 |
자바스크립트 - 배열 혹은 문자열의 #번째 요소의 값 찾는 법 (at() 함수) (0) | 2023.06.28 |
자바스크립트 - 특정 문자의 정숫값 확인 방법 (charCodeAt() 함수) (0) | 2023.04.09 |