코테

문자열 섞기

콩쥐땃쥐 2024. 11. 29. 01:25

function solution(str1, str2) {
    let answer = ''
    for(let i = 0; i<str1.length; i++){
          answer += str1[i]+str2[i];
    }
    return answer;
}

문자열을 for문으로 저렇게 배열을 통해서 돌리면 한 글자씩 나오고 두 글자를 합쳐서 answer에 넣어주었다. 

두 글자를 합쳐서 넣어주기 때문에 for문은 str1의 길이만큼 돌렸다.

 

다만 코드가 길어보인다는 단점이 있다.

 

function solution(str1, str2) {
    return [...str1].map((x, idx)=> x+str2[idx]).join("");
}

캬.... 어떻게 이런 생각을 할 수 있는건지...

str1을 구조분해할당해서 map으로 돌린다.

x안에는 str1[]을 넣고 idx에는 번호?를 넣어줌으로써 map으로 반복문을 돌린 것... 근데 join은 뭔지 모르겠다.

 

join은 배열의 모든 요소를 연결해 하나의 문자열로 만든다.
아래는 예시
const arr = ['바람', '비', '물'];

console.log(arr.join());
// 바람,비,물

console.log(arr.join(''));
// 바람비물

console.log(arr.join('-'));
// 바람-비-물​