简体   繁体   中英

I am getting a function undefined error with my javascript function

I'm trying to calculate the age of a person based on an 8 digit input. When I try to run the code it says TypeError undefined is not a function..

var calcAge = function (dob) {

    var age,

        mm = dob.substring(0, 2),
        dd = dob.substring(2, 4),
        yyyy = dob.substring(4, 8),
        d = new Date(),
        currentDay = d.getDay,
        currentMonth = (d.getMonth() + 1) < 10 ? "0" + (d.getMonth() + 1) : d.getMonth() + 1,
        currentYear = d.getFullYear;


        if (parseInt("" + mm + dd) >= parseInt("" + currentMonth + currentDay)) {
            age = currentYear - yyyy;
        } else {
            age = (currentYear - yyyy) - 1;
        };

        return age;
};

d.getDay() and d.getFullYear() are functions not string values,you were using getDay() which returns the dayofweek instead of getDate() and your final test was a little off.

var calcAge = function (dob) {
var age,
    mm = dob.substring(0, 2),
    dd = dob.substring(2, 4),
    yyyy = dob.substring(4, 8),
    d = new Date(),
    currentDay = d.getDate(),
    currentMonth = (d.getMonth() + 1) < 10 ? "0" + (d.getMonth() + 1) : d.getMonth() + 1,
    currentYear = d.getFullYear();
    if (parseInt("" + mm + dd) <= parseInt("" + currentMonth + currentDay)) {
        age = currentYear - yyyy;
    } else {
        age = (currentYear - yyyy) - 1;
    };
    return age || false;
};

using these tests it seems correct now calcAge('02191964');//returns 51 calcAge('02201964');// 51 calcAge('02211964');//50

如果您将dob参数作为8个整数传递,则您的子字符串调用将返回您看到的错误。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM