月中的天数功能只能一次性使用

Days in month function only has single use

本文关键字:一次性 功能      更新时间:2023-09-26

我使用下面的函数来确定一个月的天数:

function daysInMonth(month,year) { 
  return new Date(year,month,0).getDate(); 
}

现在,当我做下面的例子,它工作得很好:

var currMonth = currDate.getMonth(),
    currYear = currDate.getFullYear(),
    daysInMonth = daysInMonth(currYear,currMonth+1);

但是,如果我尝试再次使用相同的函数,像这样:

var test = daysInMonth(currYear,currMonth+2);

我得到以下错误:

Uncaught TypeError: number is not a function 

为什么会发生这种情况?

您正在用函数daysInMonth的值分配变量daysInMonth,有效地将函数替换为整数。给你的变量起一个不同的名字就可以了,例如

var currMonth = currDate.getMonth(),
currYear = currDate.getFullYear(),
numberOfDaysInMonth = daysInMonth(currYear,currMonth+1);
var test = daysInMonth(currYear,currMonth+2);

函数和变量名相同

function daysInTheMonth(month,year) { 
  return new Date(year,month,0).getDate(); 
}
var test = daysInTheMonth(currYear,currMonth+2);