상세 컨텐츠

본문 제목

[자바스크립트] 만 나이 계산기 코드 분석

자바스크립트

by front-hyun 2023. 4. 9. 21:30

본문

시연 영상 보고 짠 코드

let nyear;
function cal(nyear, nmonth, nday){
    console.log(`생년월일\n ${nyear}-0${nmonth}-0${nday}`);
    let date=new Date();
    let year=date.getFullYear()-nyear-1;
    console.log(`만 나이\n귀하의 만 나이는 ${year} 입니다.`);
}

cal(1995, 3, 4);

 

  1. let nyear;: nyear라는 이름의 변수를 선언하고 있습니다. 이 변수는 함수의 매개변수와 동일한 이름이지만, 함수 내부에서 선언된 변수가 함수의 매개변수를 가리게 되므로, 함수 내부에서는 nyear 변수가 매개변수로 사용되지 않고 전역 변수로 사용됩니다.
  2. function cal(nyear, nmonth, nday) { ... }: cal이라는 이름의 함수를 정의하고 있습니다. 이 함수는 nyear, nmonth, nday라는 3개의 매개변수를 받습니다.
  3. console.log(생년월일\n ${nyear}-0${nmonth}-0${nday});: console.log() 함수를 사용하여 생년월일을 출력하고 있습니다. ES6의 템플릿 리터럴을 사용하여 문자열 내에 변수 값을 삽입하고 있습니다. \n은 줄바꿈을 나타내는 이스케이프 시퀀스입니다.
  4. let date=new Date();: Date 객체를 생성하여 현재 날짜와 시간을 저장하고 있습니다.
  5. let year=date.getFullYear()-nyear-1;: 현재 연도(date.getFullYear())에서 입력된 nyear 값을 빼고 1을 빼서, 만 나이를 계산하여 year 변수에 저장하고 있습니다.
  6. console.log(만 나이\n귀하의 만 나이는 ${year} 입니다.);: console.log() 함수를 사용하여 만 나이를 출력하고 있습니다. 다시 템플릿 리터럴을 사용하여 변수 값을 삽입하고 있습니다. \n은 줄바꿈을 나타내는 이스케이프 시퀀스입니다.
  7. cal(1995, 3, 4);: cal 함수를 호출하고 있습니다. 인자로 1995, 3, 4라는 값을 전달하여 함수 내부에서 생년월일과 만 나이를 계산하고 출력하게 됩니다.

 

강의 보고 따라 친 코드

let el = document.getElementById('birthday');
let elResult=document.getElementById('result');
let elSubmit = document.getElementById('submit');

const today=new Date();

//html 요소 반환해서 가져오기
function calculateAge(){

    let birthDate = new Date(el.value);

    let age;

    if(today.getMonth() > birthDate.getMonth() || 
      (today.getMonth() == birthDate.getMonth() && today.getDate() >= birthDate.getDate() ))
      {
        age=today.getFullYear()-birthDate.getFullYear();
      }
      else{
        age=today.getFullYear()-birthDate.getFullYear()-1;
      }
      
      elResult.innerText=`귀하의 만 나이는 ${age} 입니다.`

      return age;
}

elSubmit.addEventListener('click', calculateAge);
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>만 나이 계산기</title>
</head>
<body>
    <div>
        <label for="age" class="text-sm font bold"> 생년월일</label>

        <div class="relative mt-1">
        <input type="date" id="birthday">
    </div>
</div>
    <div>
        
    <div>
        <label for="age" class="text-sm font bold"> 만 나이</label>
        <div id="result">
    </div>
    </div>

   <button id="submit">제출하기</button>
   
   <script src="vod_age_calculator.js"></script>
</body>
</html>

  1. let el = document.getElementById('birthday');: id가 "birthday"인 HTML 요소를 가져와서 el이라는 변수에 할당하고 있습니다. 이 요소는 생년월일을 입력하는 <input> 태그를 가리킵니다.
  2. let elResult=document.getElementById('result');: id가 "result"인 HTML 요소를 가져와서 elResult라는 변수에 할당하고 있습니다. 이 요소는 계산된 만 나이를 출력하는 <div> 태그를 가리킵니다.
  3. let elSubmit = document.getElementById('submit');: id가 "submit"인 HTML 요소를 가져와서 elSubmit이라는 변수에 할당하고 있습니다. 이 요소는 "계산" 버튼을 가리킵니다.
  4. const today=new Date();: Date 객체를 사용하여 현재 날짜와 시간을 저장하고 있습니다.
  5. function calculateAge() { ... }: calculateAge라는 이름의 함수를 정의하고 있습니다. 이 함수는 el이라는 변수에 저장된 생년월일을 가져와서, 현재 날짜와 비교하여 만 나이를 계산하고 출력하는 역할을 수행합니다.
  6. let birthDate = new Date(el.value);: el 변수에 저장된 생년월일을 Date 객체로 변환하여 birthDate라는 변수에 저장하고 있습니다. el 변수는 <input> 태그를 가리키므로, el.value는 입력된 생년월일 값입니다.
  7. if(today.getMonth() > birthDate.getMonth() || (today.getMonth() == birthDate.getMonth() && today.getDate() >= birthDate.getDate() )) { ... } else { ... }: 현재 날짜의 월(today.getMonth())과 일(today.getDate())을 비교하여 생년월일과 비교하여 만 나이를 계산하고 있습니다. 월이 더 크거나 월이 같고 일이 크거나 같은 경우에는 현재 연도(today.getFullYear())에서 생년월일의 연도(birthDate.getFullYear())를 빼서 만 나이를 계산하고, 그렇지 않은 경우에는 현재 연도에서 생년월일의 연도를 빼고 1을 빼서 만 나이를 계산하고 있습니다.
  8. elResult.innerText=귀하의 만 나이는 ${age} 입니다.;: innerText 속성을 사용하여 elResult 요소에 계산된 만 나이를 출력하고 있습니다. 템플릿 리터럴을 사용하여 변수 값을 삽입하고 있습니다.
  9. return age;: 계산된 만 나이를 반환합니다.
  10. elSubmit.addEventListener('click', calculateAge);: "계산" 버튼에 클릭 이벤트

관련글 더보기