map메서드를 이용해 동적으로 HTML을 생성할 때(InnerHTML) 쉼표 제거하기

N·2023년 5월 4일
0

최종 결과

 // 컨트롤러에 좌표를 출력합니다
        const locationContainer = document.getElementById(
          "map-location-container_right"
        );
        const locationArray = markerPositions.filter((el, idx) => {
          if (idx < i) {
            return "<p class='container_position'>" + el + "</p>";
          }
        });
        locationContainer.innerHTML = locationArray
          .map((el) => {
            return "<p class='container_position'>" + el + "</p>";
          })
          .join(""); // 여기가 포인트!

문제상황

  • 화면에 동적으로 html 태그를 넣고 싶을 때 map 메서드를 사용해봤다
  • 리턴되는 배열을 출력해보니 쉼표가 함께 보이는 문제가 발생했다
 // 컨트롤러에 좌표를 띄웁니다
        const locationContainer = document.getElementById(
          "map-location-container_right"
        );
        const locationArray = markerPositions.filter((el, idx) => {
          if (idx < i) {
            return "<p class='container_position'>" + el + "</p>";
          }
        });
        locationContainer.innerHTML = locationArray
          .map((el) => {
            return "<p class='container_position'>" + el + "</p>";
          })

결과 이미지

원래 목표로 했던 UI는 다음과 같다

검색해보니 나와 같은 문제를 겪었던 블로거가 있었다
출처(https://takeknowledge.tistory.com/139)

원인 : map메서드는 리턴할 때 쉼표(,)를 함께 리턴한다.
해결방법 : map으로 리턴한 결과를 다시 Join("")하여 최종 결과값을 출력한다.

콘솔에 HTML이 어떻게 생성되고 있는지 출력해봤다

  • 출력할 배열
  • html 출력 결과

배열 내부 값을 통째로 문자열로 인식해서 ","까지 출력하고있었다 ["1","2","3","4"] -> ["1,2,3,4"]

참고한 블로그는 배열 안에 있는 모든 값을 하나의 문자열로 만들어서 출력하는 방법을 사용했다. join은 배열 안에 있는 모든 값을 하나의 문자열로 만들어주는 메서드다.
join("") 메서드를 사용한 결과를 출력해보았다.

 locationArray
          .map((el) => {
            return "<p class='container_position'>" + el + "</p>";
          })
          .join("");

문제가 해결되었다!
해결방법을 알려준 블로거님께 정말 감사하다고 전하고싶다.

profile
web

0개의 댓글