How do I check if an object has a key in JavaScript?

This question already has an answer here:

  • How do I check if an object has a property in JavaScript? 22 answers

  • Try the JavaScript in operator.

    if ('key' in myObj)
    

    And the inverse.

    if (!('key' in myObj))
    

    Be careful! The in operator matches all object keys, including those in the object's prototype chain.

    Use myObj.hasOwnProperty('key') to check an object's own keys and will only return true if key is available on myObj directly:

    myObj.hasOwnProperty('key')
    

    Unless you have a specific reason to use the in operator, using myObj.hasOwnProperty('key') produces the result most code is looking for.


    You should use hasOwnProperty . For example:

    myObj.hasOwnProperty('myKey');
    
    链接地址: http://www.djcxy.com/p/27304.html

    上一篇: for..in和hasOwnProperty

    下一篇: 如何检查一个对象是否在JavaScript中有键?