Test if something is not undefined in JavaScript

前端 未结 11 1745
礼貌的吻别
礼貌的吻别 2020-11-30 19:50

I\'m checking if(response[0].title !== undefined), but I get the error:

Uncaught TypeError: Cannot read property \'title\' of undefined.<

相关标签:
11条回答
  • 2020-11-30 19:54

    typeof:

    var foo;
    if (typeof foo == "undefined"){
      //do stuff
    }
    
    0 讨论(0)
  • 2020-11-30 19:58

    You must first check whether response[0] is undefined, and only if it's not, check for the rest. That means that in your case, response[0] is undefined.

    0 讨论(0)
  • 2020-11-30 20:00

    Actually you must surround it with an Try/Catch block so your code won't stop from working. Like this:

    try{
        if(typeof response[0].title !== 'undefined') {
            doSomething();
        }
      }catch(e){
        console.log('responde[0].title is undefined'); 
      }
    
    0 讨论(0)
  • 2020-11-30 20:10

    I had trouble with all of the other code examples above. In Chrome, this was the condition that worked for me:

    typeof possiblyUndefinedVariable !== "undefined"
    

    I will have to test that in other browsers and see how things go I suppose.

    0 讨论(0)
  • 2020-11-30 20:11

    Just check if response[0] is undefined:

    if(response[0] !== undefined) { ... }
    

    If you still need to explicitly check the title, do so after the initial check:

    if(response[0] !== undefined && response[0].title !== undefined){ ... }
    
    0 讨论(0)
  • 2020-11-30 20:11

    Check if you're response[0] actually exists, the error seems to suggest it doesn't.

    0 讨论(0)
提交回复
热议问题