html5网页制作+javascript

2025-05-04 20:41:09
推荐回答(3个)
回答1:






计算






回答2:




    
    test

 function Student(id, name, gender, birthday, score) {
        this.id = id;
 this.name = name;
 this.gender = gender;
 this.birthday = birthday;
 this.score = score;
 this.study = function () {
            this.score = this.score === 100 ? this.score : this.score += 1;
 };
 this.getAge = function () {
            return new Date().getFullYear() - new Date(birthday).getFullYear()
        };
 }
 
    var student = new Student(1,'张三','男','1996-2-12',20);
 console.log('学习成绩:'+student.score);
 console.log('年龄:'+student.getAge());
 student.study();
 console.log('学习成绩:'+student.score); //学分加1
 student.study();
 console.log('学习成绩:'+student.score); //学分加1


请打开浏览器控制台查看日志输出效果。

回答3:

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();