Test if something is not undefined in JavaScript

ぃ、小莉子 提交于 2019-12-28 03:20:08

问题


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

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


回答1:


response[0] is not defined, check if it is defined and then check for its property title.

if(typeof response[0] !== 'undefined' && typeof response[0].title !== 'undefined'){
    //Do something
}



回答2:


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){ ... }



回答3:


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.




回答4:


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'); 
  }



回答5:


typeof:

var foo;
if (typeof foo == "undefined"){
  //do stuff
}



回答6:


It'll be because response[0] itself is undefined.




回答7:


Check if condition == null; It will resolve the problem




回答8:


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




回答9:


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.




回答10:


I know i went here 7 months late, but I found this questions and it looks interesting. I tried this on my browser console.

try{x,true}catch(e){false}

If variable x is undefined, error is catched and it will be false, if not, it will return true. So you can use eval function to set the value to a variable

var isxdefined = eval('try{x,true}catch(e){false}')


来源:https://stackoverflow.com/questions/7041123/test-if-something-is-not-undefined-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!