简体   繁体   English

在JavaScript上赋值后变量未定义

[英]Variable is undefined after assignment on JavaScript

This is getting frustrating, variable is always undefined after assignment. 令人沮丧的是,赋值后变量始终是未定义的。 Please explain what I am doing wrong here. 请在这里解释我做错了什么。

$(document).ready(function() {
    $("#submitButton").click(function() {
        var startDate = $('#startDate').val();
        var endDate = $('#endDate').val();

        if (!isDate(startDate) && !isDate(endDate))
        {
            alert ('Start Date and End Date is invalid');
            return false;
        }
        ... other condition removed for clarity
    });
});

function isDate(dateText)
{
    var comp = [];
    var comp2 = '';
    var y_length = 0;

    comp = dateText.split('/');
    comp2 = comp[2];
    y_length = comp2.length;

    //invalid if year length is less than or greater than 4 
    if (y_length < 4 || y_length > 4) {
        return false;
    }

    var m = parseInt(comp[0], 10);
    var d = parseInt(comp[1], 10);
    var y = parseInt(comp[2], 10);

    var date = new Date(y, m - 1, d);

    if (date.getFullYear() == y && date.getMonth() + 1 == m && date.getDate() == d) {
        return true;
    } else {
        return false;
    }
}

I amg getting ' Cannot read property length of undefined ' on line y_length assignment , this line: 我amg在y_length赋值行上得到“ 无法读取未定义属性长度 ”,此行:

//comp2 here is undefined
y_length = comp2.length;

Additionally, do you have any suggestion on date validation using JavaScript. 此外,您对使用JavaScript进行日期验证有什么建议吗? Thank you. 谢谢。

If dateText doesn't have at least 2 instances of / in it you are going to end up with less than 3 elements after the split so 如果dateText中至少不包含/的2个实例,则分割后最终将少于3个元素,因此

comp2 = comp[2];

sets comp2 to undefined and 将comp2设置为undefined,

y_length = comp2.length;

will error out. 会出错。 If you are entering a dateText which has 2 (or more instances) of / in it you shouldn't be getting this error. 如果输入的dateText中包含2个(或更多实例)/,则不应出现此错误。 If you are, you will want to check the value of dateText (with an alert or console.log) 如果是这样,您将要检查dateText的值(带有警报或console.log)

You might want to do something like 您可能想要做类似的事情

if (comp.length > 2) {
    comp2 = comp[2];
    ...
else {
    // error handling
    ...

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

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