let student = new Object;
student.no = 1;
student.name = "大企鹅";
student.sex = "男";
student.born = "1995-09-25";
student.score = 0;
student.learn = function () {
student.score += 10
};
student.age = function () {
let returnAge;
// 根据生日计算年龄("1995-09-25")
//以下五行是为了获取出生年月日,如果是从身份证上获取需要稍微改变一下
let strBirthdayArr = student.born.split("-");
let birthYear = strBirthdayArr[0];
let birthMonth = strBirthdayArr[1];
let birthDay = strBirthdayArr[2];
d = new Date();
let nowYear = d.getFullYear();
let nowMonth = d.getMonth() + 1;
let nowDay = d.getDate();
if (nowYear == birthYear) {
returnAge = 0;//同年 则为0岁
} else {
let ageDiff = nowYear - birthYear; //年之差
if (ageDiff > 0) {
if (nowMonth == birthMonth) {
let dayDiff = nowDay - birthDay;//日之差
if (dayDiff < 0) {
returnAge = ageDiff - 1;
} else {
returnAge = ageDiff;
}
} else {
let monthDiff = nowMonth - birthMonth;//月之差
if (monthDiff < 0) {
returnAge = ageDiff - 1;
} else {
returnAge = ageDiff;
}
}
} else {
returnAge = -1;//返回-1 表示出生日期输入错误 晚于今天
}
}
return returnAge;//返回周岁年龄
};
document.body.innerHTML += student.score + "
";
document.body.innerHTML += student.age();