当前位置: 代码迷 >> JavaScript >> 在JavaScript上赋值后变量未定义
  详细解决方案

在JavaScript上赋值后变量未定义

热度:92   发布时间:2023-06-06 09:40:25.0

令人沮丧的是,赋值后变量始终是未定义的。 请在这里解释我做错了什么。

$(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;
    }
}

我amg在y_length赋值行上得到“ 无法读取未定义属性长度 ”,此行:

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

此外,您对使用JavaScript进行日期验证有什么建议吗? 谢谢。

如果dateText中至少不包含/的2个实例,则分割后最终将少于3个元素,因此

comp2 = comp[2];

将comp2设置为undefined,

y_length = comp2.length;

会出错。 如果输入的dateText中包含2个(或更多实例)/,则不应出现此错误。 如果是这样,您将要检查dateText的值(带有警报或console.log)

您可能想要做类似的事情

if (comp.length > 2) {
    comp2 = comp[2];
    ...
else {
    // error handling
    ...
  相关解决方案