Checking if a key exists in a JavaScript object?

前端 未结 22 2264
礼貌的吻别
礼貌的吻别 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:40

    Three ways to check if a property is present in a javascript object:

    1. !!obj.theProperty
      Will convert value to bool. returns true for all but the false value
    2. 'theProperty' in obj
      Will return true if the property exists, no matter its value (even empty)
    3. obj.hasOwnProperty('theProperty')
      Does not check the prototype chain. (since all objects have the toString method, 1 and 2 will return true on it, while 3 can return false on it.)

    Reference:

    http://book.mixu.net/node/ch5.html

提交回复
热议问题