How to avoid 'cannot read property of undefined' errors?

前端 未结 16 2520
野性不改
野性不改 2020-11-22 06:02

In my code, I deal with an array that has some entries with many objects nested inside one another, where as some do not. It looks something like the following:



        
16条回答
  •  佛祖请我去吃肉
    2020-11-22 06:21

    What you are doing raises an exception (and rightfully so).

    You can always do

    try{
       window.a.b.c
    }catch(e){
       console.log("YO",e)
    }
    

    But I wouldn't, instead think of your use case.

    Why are you accessing data, 6 levels nested that you are unfamiliar of? What use case justifies this?

    Usually, you'd like to actually validate what sort of object you're dealing with.

    Also, on a side note you should not use statements like if(a.b) because it will return false if a.b is 0 or even if it is "0". Instead check if a.b !== undefined

提交回复
热议问题