简体   繁体   English

我的javascript函数出现函数未定义错误

[英]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. 我正在尝试根据8位数字输入来计算一个人的年龄。 When I try to run the code it says TypeError undefined is not a function.. 当我尝试运行代码时,它说TypeError undefined不是函数。

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. d.getDay()和d.getFullYear()是不是字符串值的函数,您使用的是getDay(),它返回星期几而不是getDate(),并且最终测试有些差。

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 使用这些测试现在看来是正确的calcAge('02191964'); //返回51 calcAge('02201964'); // 51 calcAge('02211964'); // 50

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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