我正在尝试根据8位输入计算一个人的年龄。当我尝试运行代码时,它说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;
};
答案 0 :(得分:1)
d.getDay()和d.getFullYear()是函数而不是字符串值,你使用getDay()返回dayofweek而不是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;
};
使用这些测试现在似乎是正确的 calcAge('02191964'); //返回51 calcAge('02201964'); // 51 calcAge( '02211964'); // 50
答案 1 :(得分:1)
如果您将dob参数作为8个整数传入,则子字符串调用将返回您看到的错误。