How to check if object within object exists

后端 未结 6 769
慢半拍i
慢半拍i 2021-01-12 08:21

It seems that the following technique for checking the existence of an object member produces an error because the \'bar\' parent object hasn\'t been declared before the che

6条回答
  •  一向
    一向 (楼主)
    2021-01-12 08:42

    var newVal = ('foo' in window && // could be typeof foo !== 'undefined' if you want all scopes
                 'bar' in foo &&
                 'myVal' in foo.bar) ? foo.bar.myVal : null;
    

    To be fair to javascript, that reads almost like natural language.

提交回复
热议问题