728x90
join()
"배열".join([구분자])
자바스크립트의 join() 메서드는 배열 원본을 변경하지 않고 배열의 모든 요소를 연결하여 하나의 문자열을 생성합니다.
const elements = ['A', 'B', 'C'];
console.log(elements.join()); // 결과: "A,B,C"
const numbers = [1, 2, 3];
console.log(numbers.join()); // 결과: "1,2,3"
const bool = [true, false];
console.log(bool.join()); // 결과: "true,false"
const fruitsObject = ["사과", "바나나", {name: "딸기", color: "빨강"}];
console.log(fruitsObject.join()); // 결과 : "사과,바나나,[object Object]"
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(matrix.join()); // 결과 : "1,2,3,4,5,6,7,8,9"
위의 예제로 보았을 때 join() 함수에 인자를 넣지 않으면 쉼표(', ')를 사용하여 배열의 문자열을 합친다는 것을 알 수 있습니다.
const elements = ['A', 'B', 'C'];
//구분자 없이 이어 붙이기
console.log(elements.join("")); // 결과: "ABC"
// 띄어쓰기로 이어 붙이기
console.log(elements.join(" ")); // 결과: "A B C"
// '-'로 이어 붙이기
console.log(elements.join("-")); // 결과: "A-B-C"
구분자를 지정해 주면 해당 배열의 모든 요소들을 구분자로 구분하여 문자열로 합칩니다.
concat()
"배열".concat([value1[, value2[, ...[, valueN]]]])
concat() 메서드는 파라미터로 받은 배열이나 값들을 기존의 배열에 순서대로 붙여 새로운 배열을 만듭니다.
const numbers = [1, 2];
const alp = ["A", "B"];
const result = numbers.concat(alp);
console.log(result); // 결과 : [1, 2, 'A', 'B']
console.log(numbers); // [1, 2]
console.log(alp); // ['A', 'B']
위의 예제를 보면 result에 number과 alp 배열을 합쳤는데 numbers와 alp는 건드리지 않고 새로운 배열을 반환한 것을 알 수 있습니다.
concat() 함수와 동일한 기능을 하는 함수는 ▶ 전개 연산자(...)와 ▶push()가 있습니다.
const arr1 = ['a', 'b'];
const arr2 = ['1', '2'];
const arr3 = arr1.concat(arr2);
console.log(arr3); // 결과 : ['a', 'b','1', '2']
const arr1 = ['a', 'b'];
const arr2 = ['1', '2'];
const arr3 = [...arr1, arr2]
console.log(arr3); // 결과 : ['a', 'b','1', '2']
const arr1 = ['a', 'b'];
const arr2 = ['1', '2'];
const arr3 = [];
arr3.push(arr1);
arr3.push(arr2);
console.log(arr3); // 결과 : [['a', 'b'],['1', '2']]
여기서 주의할 점은 push() 메서드에 넘어온 인수는 배열의 끝에 추가가 되기 때문에 빈 배열에 arr1과 arr2가 인수(배열) 그대로 들어가기 때문에 위와 같이 배열 안에 배열이 중첩으로 들어가게 됩니다.
따라서 전개 연산자(...)를 사용하여 배열의 요소를 전개해주어야 합니다.
const arr1 = ['a', 'b'];
const arr2 = ['1', '2'];
const arr3 = [];
arr3.push(...arr1);
arr3.push(...arr2);
console.log(arr3); // 결과 : ['a','b','1','2']
'Language > JavaScript' 카테고리의 다른 글
[JavaScript] fill() 함수 알아보기 (0) | 2024.01.19 |
---|---|
[JavaScript] 정렬 함수 sort() 함수와 toSorted() 함수 알아보기 (0) | 2024.01.17 |
[JavaScript] nullish 병합 연산자 '??' (0) | 2024.01.15 |
[JavaScript] find(), findIndex() 함수 알아보기 (0) | 2024.01.14 |
[JavaScript] 거듭제곱 알아보기 (0) | 2024.01.13 |