简体   繁体   English

未捕获的TypeError:undefined不是函数

[英]Uncaught TypeError: undefined is not a function

I am trying to find the difference between 2 dates in whole months, I found a little script on Stack Exchange, but it keeps giving me an error of "Uncaught TypeError: undefined is not a function". 我试图找出整个月中两个日期之间的差异,我在Stack Exchange上找到了一个小脚本,但是它一直给我一个错误:“未捕获的TypeError:未定义不是函数”。

I get this in chrome, it is a fairly simple HTML page. 我得到的是chrome,这是一个相当简单的HTML页面。

It doesn't seem to like the first line of the function (var monthsLeft = to.getMonth() etc...) 它似乎不喜欢函数的第一行(var monthsLeft = to.getMonth()等)。

(slightly simplified version for clarity:) (为清楚起见,略简化了版本:)

<script>
function monthDiff(from, to) {
    var monthsLeft = to.getMonth() - from.getMonth() + (12 * (to.getFullYear() - from.getFullYear()));
    if(to.getDate() < from.getDate()) {
        monthsLeft--;
    }
    return monthsLeft;
  }


function lumpChange() {

        var today = new Date();
        var april5th = new Date();
        var MonthsLeft = 0;

        today = '10/05/2015';
        april5th = '04/05/2015';
        MonthsLeft = monthDiff(today, april5th);  
  }

</script>

Your monthDiff() function looks as though it expects Date objects to be passed as parameters (it uses methods like .getMonth() etc). 您的monthDiff()函数看起来好像希望将Date对象作为参数传递(它使用.getMonth()等方法)。 You are passing strings. 您正在传递字符串。

You don't modify Date objects by assigning strings to the variable the object was originally in. 您不必通过将字符串分配给对象最初所在的变量来修改Date对象。

You can define the Date when instantiating it: 您可以在实例化Date时定义Date

function lumpChange(){
    var today = new Date(2015, 10, 05),
        april5th = new Date(2015, 04, 05);

    MonthsLeft = monthDiff(today, april5th); // -6
}

JSFiddle 的jsfiddle

If you need to set the date/time of a Date object after instantiating it, you can use the setter methods . 如果您需要在实例化Date对象后设置日期/时间,则可以使用setter方法

Documentation: 文档:

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

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