<!DOCTYPE html> <html lang='jp'> <head> <meta charset='UTF-8'> <title>誕生日から年齢の計算</title> </head> <body> <input type="text " id="birthday" placeholder="MM/DD/YYYY"> <button id="btn-submit"> 計算 </button> <div id="age"> </div> <script src='js/app.js'></script> </body> </html>
// ボタンのイベントリスナー document.getElementById('btn-submit').addEventListener('click', function() { let age, // 年齢 birthdayVal, // 誕生日の日付の値 birthdayInst, // 誕生日の日付を保持したDateインスタンス todayInst; // 今日の日付を保持したDateインスタンス birthdayVal = document.getElementById('birthday').value; birthdayInst = new Date(birthdayVal); todayInst = new Date(); age = todayInst.getFullYear() - birthdayInst.getFullYear(); if (Number.isNaN(age)) { alert(`正しいフォーマットで誕生日を入力してください。`); } if (todayInst < birthdayInst.setFullYear(todayInst.getFullYear())) { age--; } document.getElementById('age').textContent = `${age}歳`; return false; });
「入門JavaScript P146」のコードを少し編集しました。
【私が理解出来ている点】
- todayInst.getFullYear():西暦を表す四桁の値。
- 計算式においてDateインスタンスはミリ秒単位の値に型変換される。
【疑問点】
- birthdayInst.setFullYear(todayInst.getFullYear())
誕生日の情報を保持しているインスタンスの西暦部分を今日の西暦に設定している。
2. todayInst < birthdayInst.setFullYear(todayInst.getFullYear())
西暦部分を揃えることで、今日と誕生日の日付部分(月と日)の情報を表す値の大きさを比較している。
条件式が真なら今年はまだ誕生日を迎えていない、つまり満年齢ではない。
∴年齢をデリクメントする。
上記の解釈で合っていますでしょうか。
よろしくお願い致します。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/01/28 08:19