如何使用if条件避免未定义的变量?

时间:2015-11-18 13:11:07

标签: javascript jquery

在我的代码中,我提供了一种检查是否单击了选项的方法,如下所示:

$("#selected-service").click(function ()

现在一切正常,但在这个方法中我对这个变量进行了定价:

var appointment = BackendCalendar.lastFocusedEventData.data;

在某些情况下,此变量返回undefined,这是正常的,如果用户处于编辑模式或添加约会模式,则导致此变量不存在。在第一种情况下,变量也是未定义的。 无论如何,我执行这个条件:

try
{
   var appointment = BackendCalendar.lastFocusedEventData.data;

   if (appointment != 'undefined')
   {
      //do this...
   }
   else 
   {
      //do this...
   }
}
catch(Ex){  console.log("Error=>" , Ex);    }

但问题是else条件永远不会触发,导致代码进入catch异常。现在,问题很简单:如果变量未定义,我如何引入else?

可能的解决方案:

if(typeof(BackendCalendar.lastFocusedEventData !== 'undefined'))
{
    appointment = BackendCalendar.lastFocusedEventData.data;
}

4 个答案:

答案 0 :(得分:1)

尝试此操作,而不是检查变量的内容,检查其类型。

if(typeof appointment !== "undefined"){
//do this
} else {
//do that
}

修改

这将有效但删除括号:

if(typeof BackendCalendar.lastFocusedEventData !== 'undefined')
{
    appointment = BackendCalendar.lastFocusedEventData.data;
}

答案 1 :(得分:0)

if (typeof appointment != 'undefined') ...

答案 2 :(得分:0)

显然问题不在于约会变量,而是与:

BackendCalendar.lastFocusedEventData

可能为null或未定义。

如果你设置约会

   var lastDate = BackendCalendar.lastFocusedEventData, appointment = lastDate ? lastDate.data : undefined

它应该有用。

另外,我个人只是使​​用

if(!appointment) {
...

其中包含 null undefined 检查(如果您确定从不

答案 3 :(得分:0)

我创建了一个验证所有对象实例的函数

function definedVar( string, containerVar ) {
    var splitted = string.split( "." );
    var testVar = containerVar;
    for( var i = 0; i < splitted.length; i++ ) {
        var propertyName = splitted[ i ];
        if( testVar[ propertyName ] == undefined ) {
            return false;
        }
        testVar = testVar[ propertyName ];
    }
    return true;
}

在行动HERE

中查看