Test if something is not undefined in JavaScript

前端 未结 11 1843
礼貌的吻别
礼貌的吻别 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 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'); 
      }
    

提交回复
热议问题