test the existence of property in a deep object structure

前端 未结 6 1322
悲&欢浪女
悲&欢浪女 2021-01-11 23:13

In javascript, lets say I want to access a property deep in an object, for example:

entry.mediaGroup[0].contents[0].url

At any point along that structure, a

6条回答
  •  無奈伤痛
    2021-01-11 23:53

    This is a very lazy way to do it, but it meets the criteria for many similar situations:

    try {
      console.log(entry.mediaGroup[0].contents[0].url);
    } catch (e) {}
    

    This should not be done on long code blocks where other errors may potentially be ignored, but should be suitable for a simple situation like this.

提交回复
热议问题