강의

멘토링

커뮤니티

Cộng đồng Hỏi & Đáp của Inflearn

Hình ảnh hồ sơ của maystar89560906
maystar89560906

câu hỏi đã được viết

[Code Camp] Javascript ấm áp

new Date để tạo một ngày

선생님 const로 변수를 할당해도 왜 작동할까요?

Đã giải quyết

Viết

·

2.7K

·

Đã chỉnh sửa

1

 <!DOCTYPE html>
<html lang="ko">
  <head>
    <title>D-DAY</title>
    <script>
     // 전역 변수로 만들어서 모든 함수에서 접근 가능
      let dateFormat = null;
      const dateFormMaker = function () {
        // 변수 camelCase 작성 -> input 에 작성한 것 (문자열임)
        const inputYear = document.querySelector("#target-year-input").value;
        const inputMonth = document.querySelector("#target-month-input").value;
        const inputDate = document.querySelector("#target-date-input").value;

        // 데이터 form 만들어 주기
        // ex) "2023-03-03"
        dateFormat = inputYear + "-" + inputMonth + "-" + inputDate;
        return dateFormat;
        console.log(inputYear, inputMonth, inputDate);
      };

      const counterMaker = function () {
        dateFormat = dateFormMaker();
        const nowDate = new Date();
        // 특정 지정한 날
        //const targetDate = new Date("2023-03-03");
        // input 창에 입력한 특정 날
        // "" 로 쓰면 문자열 데이터로 인식되기 때문에 변수로 써야하기 때문에 dateFormat으로 사용
        const targetDate = new Date(dateFormat);
        // 먼저 빼고 나서 나눗셈 진행 (밀리세컨드 구별)
        const remaining = (targetDate - nowDate) / 1000;
        // 1시간 3600초
        // 하루 24시간
        // 남은 일자
        // Math.floor : 소수점 이하를 내림
        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);
      };
    </script>
  </head>
  <body>
    <input id="target-year-input" class="target-input" />
    <input id="target-month-input" class="target-input" />
    <input id="target-date-input" class="target-input" />
    <button onclick="counterMaker()">버튼</button>
  </body>
</html>
날짜를생성하는newdatejavascript

Câu trả lời 2

1

안녕하세요 초록천사님!

이는 변수가 생성되고 사라지는 시점을 생각해 보시면 도움이 될 것 같습니다.

dateFormMaker 그리고 counterMaker라고 하는 함수는 버튼을 누름과 동시에 살아나 동작하는 함수입니다.

그 이전까지는 두 함수 모두 잠들어 있는 함수죠.

우리가 버튼을 누르면 함수가 실행됩니다. 이때, inputYear, inputMonth, inputDate라는 세개의 상수가 선언되고 각각의 역할에 맞는 값을 가져오게 되죠!

그리고 위 세 변수를 담고 있는 dateFormMaker 함수는 결과적으로 완성된 데이터를 return하게 됩니다. 함수가 종료되는 것이죠.

함수가 종료된다는 의미는 그 생명을 다했다는 것으로 안에 담겨져 동작하던 변수들도 생명을 다하게 되는 것입니다.

즉, dateFormMakerreturn 키워드를 만나 종료됨과 동시에 그 안에 담긴 inputYear, inputMonth, inputDate 세개의 상수도 역할을 다 하고 더이상 존재하지 않게 되는 것이죠.

만약 다시 버튼을 누른다면 함수가 새로 실행되면서 완전히 새로운 inputYear, inputMonth, inputDate가 또다시 생성되어 함수가 종료되기 전까지 존재하겠죠?

함수가 종료되면 또 다시 사라지게 될 것이고요!

위와 같은 내용으로 이해하시면서 정리해 보시면 도움이 될 것 같네요!

0

maystar89560906님의 프로필 이미지
maystar89560906
Người đặt câu hỏi


  const inputYear = document.querySelector("#target-year-input").value;
  const inputMonth = document.querySelector("#target-month-input").value;
  const inputDate = document.querySelector("#target-date-input").value;

저기서 input 입력한 날짜를 가져올 때 inputYear, inputMonth 등도 let으로 설정해야 하는 거 아닌가요?
input에 입력한 값을 가져오고 나서 그 input 값을 다른 값으로 바꿀 수 있잖아요? 그럼 재할당 개념인데 그럼 const로 써야 하는 걸로 머리는 이해하는데
웃긴건 이 코드로 잘 돌아갑니다.

또 선생님 하나 더 궁금한 것이

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;

이런 값들도 버튼을 클릭 하면 남은 시간이 바뀌어서 콘솔 창에 찍히는데 그럼 let으로 설정해야하는데
왜 const 상수인데 잘 작동하는지 이해가 안됩니다.


 

재할당 안 일어날거 같은데요.

버튼 누르고 이벤트 콜백 실행되면

상수가 생성되고 콜백이 끝나면 상수가 사라져서 이벤트마다 재생성된다고 보셔야겠네요.

Hình ảnh hồ sơ của maystar89560906
maystar89560906

câu hỏi đã được viết

Đặt câu hỏi