• 카테고리

    질문 & 답변
  • 세부 분야

    프론트엔드

  • 해결 여부

    해결됨

d-day 코드오류

23.05.31 00:42 작성 조회수 184

0

강의보면서 그대로 작성했는데 targetDate 부분이 오류가 납니다.

여기서 안되니까 remaining 에서도 오류나고..

콘솔 찍으면 NaN 만 출력이 되네요ㅠㅠ 왜그럴까요?

nan.PNG

  <script>
      const dateFormMaker = function () {
        const inputYear = document.querySelector("#target-year-input").value;
        const inputMonth = document.querySelector("#target-month-input").value;
        const inputDate = document.querySelector("#target-date-input").value;

        const dateFormat = `${inputYear}-${inputMonth}-${inputDate}`;

        return dateFormat;
      };

      const counterMaker = function () {
        const targetDateInput = dateFormMaker();
        const nowDate = new Date();
        const targetDate = new Date(targetDateInput).setHours(0,0,0,0); /* error */
        const remaining = (targetDate - nowDate) / 1000;

        const remainingDate = Math.floor(remaining / 3600 / 24);
        const remainingHours = Math.floor(remaining / 3600) % 24;
        const remainingMin = Math.floor(remaining / 60) % 60;
        const remainingSec = Math.floor(remaining) % 60;

        console.log(remainingDate, remainingHours, remainingMin, remainingSec);
        console.log(targetDate);
      };
    </script>

답변 1

답변을 작성해보세요.

0

안녕하세요! 님!

counterMaker() 함수를 실행하셨는데, 최종 결과 콘솔 2줄이 모두 NaN으로 출력되셨군요!
NaN은 Not a Number의 약자로, 계산할 수 없는 값, 이상한 값들에 대해서 계산이 들어간 경우의 결과로 받아보실 수 있습니다.

따라서, 계산이 왜 진행이 되고 있지 못하는지 확인을 해볼 필요가 있어요!
가장 먼저 확인해 보실 부분은 counterMaker() 함수가 실행되었을 때, 내부에서 가장 먼저 실행되는 dateFormMaker() 함수가 잘못되었을 가능성이 있습니다.

dateFormMaker() 함수 내부에서는 id="target-year-input", id="target-month-input", id="target-date-input" 이라는 속성을 가진 태그들의 값(value)를 가져오고 있네요.
따라서, 위 3개의 태그들에 어떠한 값도 입력되지 않은 상태에서 counterMaker() 함수가 실행되는 경우 최종 결과가 NaN이 될 수 있을 것 같아요!