How to check if object has property javascript?
This question already has an answer here:
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