Javascript 如何检查对象是否具有属性javascript?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39275193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if object has property javascript?
提问by Michael
I have this function:
我有这个功能:
function ddd(object) {
if (object.id !== null) {
//do something...
}
}
But I get this error:
但我收到此错误:
Cannot read property 'id' of null
How can I check if object has property and to check the property value??
如何检查对象是否具有属性并检查属性值?
回答by deltree
hasOwnPropertyis the method you're looking for
hasOwnProperty是你正在寻找的方法
if (object.hasOwnProperty('id')) {
// do stuff
}
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 objectis null, not idso be wary of that scenario.
在这种特殊情况下,您看到的错误表明它object为空,不要id对这种情况保持警惕。
For testing awkward deeply nested properties of various things like this, I use brototype.
为了测试像这样的各种东西的笨拙的深度嵌套属性,我使用了brototype。

