什么,究竟是"未定义"的价值?

Cas*_*ton -2 javascript jquery

我试图捕获某个变量的值,并在它为null或未定义时执行某些操作.

$(".change-engineer").change(function (e) {
    var prevContactID = $(this).data('prev-value');

    alert(prevContactID.value); // this shows "undefined"

    if (prevContactID.value === null)
    {
        // we never get here
    }

    if (prevContactID.value === "undefined")
    {
        // we never get here
    }

    $.ajax({
        type: 'POST',
        url: '@Url.Action("ChangeProposalEngineer", "RequestForQuotes")',
        data: { "prevContactID": prevContactID },
        cache: false,
        complete: function (data) {
            ...
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

在服务器端,我可以打开一个断点,ChangeProposalEngineer值为prevContactID"null".

但在客户端,这个:alert(prevContactID.value);弹出"未定义".但是,我似乎无法弄清楚当该值为null时如何进入if-then.

Tim*_*imo 6

不要检查字符串"undefined".检查原语undefined:

if(prevContactID.value === undefined) {
    // we never get here
}
Run Code Online (Sandbox Code Playgroud)

或者,检查一般的假值,其中包括nullundefined:

if(!prevContactID.value) {
    // we never get here
}
Run Code Online (Sandbox Code Playgroud)