Checking if a key exists in a JavaScript object?

前端 未结 22 2206
礼貌的吻别
礼貌的吻别 2020-11-21 22:57

How do I check if a particular key exists in a JavaScript object or array?

If a key doesn\'t exist, and I try to access it, will it return false? Or throw an error?<

22条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-21 23:29

    While this doesn't necessarily check if a key exists, it does check for the truthiness of a value. Which undefined and null fall under.

    Boolean(obj.foo)

    This solution works best for me because I use typescript, and using strings like so 'foo' in obj or obj.hasOwnProperty('foo') to check whether a key exists or not does not provide me with intellisense.

提交回复
热议问题