How to check if object has property javascript?

This question already has an answer here:

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

  • hasOwnProperty is the method you're looking for

    if (object.hasOwnProperty('id')) {
        // do stuff
    }
    

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

    As an alternative, you can do something like:

    if (typeof object.id !== 'undefined') {
        // note that the variable is defined, but could still be 'null'
    }
    

    In this particular case, the error you're seeing suggests that object is null, not id so be wary of that scenario.

    For testing awkward deeply nested properties of various things like this, I use brototype.

    链接地址: http://www.djcxy.com/p/27308.html

    上一篇: 如何检查Javascript中是否存在字符串/数组/对象?

    下一篇: 如何检查对象是否具有属性javascript?