Bin's Blog

concat 메서드 본문

JavaScript

concat 메서드

hotIce 2023. 6. 1. 08:44
728x90

concat은 Javascript에서 배열을 다루는 데 사용하는 메서드 중 하나입니다. 이 메서드는 두 개 이상의 배열을 하나로 결합하는 데 사용되며, 원래의 배열은 수정되지 않고 새로운 배열을 반환한다. 

 

ex) 기본 예시

let array1 = [1, 2, 3];
let array2 = [4, 5, 6];

let array3 = array1.concat(array2);

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

array1과 array2는 원래 그대로 유지되고, 두 배열을 결합한 새 배열이 array3에 할당된다. 

 

ex) 문자열을 배열에 추가

let array1 = ["Apple", "Banana"];
let array2 = ["Cherry", "Date"];
let result = array1.concat(array2, "Extra", "Fruits");

//["Apple", "Banana", "Cherry", "Date", "Extra", "Fruits"]
console.log(result);

ex) 객체를 배열에 추가

let array1 = [{ name: 'Apple', type: 'Fruit' }, { name: 'Carrot', type: 'Vegetable' }];
let array2 = [{ name: 'Dog', type: 'Animal' }, { name: 'Elephant', type: 'Animal' }];
let result = array1.concat(array2, { name: 'Extra', type: 'Unknown' });


//[{ name: 'Apple', type: 'Fruit' }, { name: 'Carrot', type: 'Vegetable' }, { name: 'Dog', type: 'Animal' },{ name: 'Elephant', type: 'Animal' }, { name: 'Extra', type: 'Unknown' }]
console.log(result);
728x90

'JavaScript' 카테고리의 다른 글

콜백 함수  (0) 2023.06.21
forEach 메서드  (0) 2023.06.02
every 메서드  (0) 2023.05.30
filter 메서드  (0) 2023.05.27
includes 메서드  (0) 2023.05.26