Javascript 如何检查可能未定义的对象上是否存在属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39135713/
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 property exists on potentially undefined object?
提问by steviejay
So there are questions on S.O. that answer how to check if a property on an object exists. ExampleAnswer is to use Object.prototype.hasOwnProperty()
.
因此,SO 上有一些问题可以回答如何检查对象上的属性是否存在。示例答案是使用Object.prototype.hasOwnProperty()
.
However, how would you check the property of a potentially undefined object?
但是,您将如何检查潜在未定义对象的属性?
If one were to attempt to just directly check if a property exists on an undefined object then it would be a reference error.
如果试图直接检查未定义对象上是否存在属性,那么这将是一个引用错误。
Semantically, it seems better to check code directly if (obj.prop) //dosomething
-- it shows clearer intent. Is there any way to achieve this? Preferably, is there a built-in Javascript method to do such a thing or by convention?
从语义上讲,直接检查代码似乎更好if (obj.prop) //dosomething
——它显示出更清晰的意图。有没有办法实现这一目标?最好,是否有内置的 Javascript 方法来做这样的事情或按照惯例?
Motive:A package adds property user.session.email -- but I'm checking to see if email exists, not the session, though the session could be nonexistent.
动机:一个包添加了属性 user.session.email -- 但我正在检查电子邮件是否存在,而不是会话,尽管会话可能不存在。
Update:Many of the answers say to use the && operator to short-circuit. I'm aware that this is a possible solution, but it is not exactly what is desired as it seems like we're working AROUND the JS object syntax -- that is, though you want to really check for a property on an object, you are being forced to check if the object exists in order to do so.
更新:许多答案都说使用 && 运算符来短路。我知道这是一个可能的解决方案,但这并不是我们想要的,因为看起来我们正在围绕 JS 对象语法工作——也就是说,尽管你想真正检查对象上的属性,为了这样做,您被迫检查对象是否存在。
Note to being marked as closedWhy was this marked as closed? The link that presumes this is a duplicate may not yield the same answers. We're looking for a better, more semantic solution and marking this closed makes the assumption that "nested" === "potentially undefined".
标记为已关闭的注意事项为什么将其标记为已关闭?假定这是重复的链接可能不会产生相同的答案。我们正在寻找一个更好的、更语义化的解决方案,并且将其标记为关闭会假设“嵌套”===“可能未定义”。
This question is disputably closed:Since I can't answer my own question now. As of recently, a proposal was put in Stage 1 herethat would solve this very issue. Again, the question wants a more semantic solution as is shown in the proposal.
这个问题有争议地结束了:因为我现在无法回答我自己的问题。直到最近,这里的第 1 阶段提出了一项可以解决这个问题的提案。同样,该问题需要更语义化的解决方案,如提案中所示。
回答by Seth
If you're certain the parent object exists, then:
如果您确定父对象存在,则:
if(obj && obj.key) {
console.log(obj.key);
}
However, this example will fail miserably if obj
doesn't exist.
但是,如果obj
不存在,这个例子将会失败。
if (obj && obj.key) {
console.log(obj.key);
}
... which is why you might want to check if the object is defined when checking for the property. This ensures that you won't get runtime errors if the condition is hit and the property's object hasn't been set.
...这就是为什么您可能想在检查属性时检查对象是否已定义。这可确保在满足条件且尚未设置属性的对象时不会出现运行时错误。
if(typeof obj != "undefined" && obj.key) {
console.log('you will not see this logged')
}
You'll notice that the above example does not throw an exception.
你会注意到上面的例子没有抛出异常。
var obj = {key: 1};
if(typeof obj != "undefined" && obj.key) {
console.log('we have obj! and val is : ' + obj.key)
}
This is a much more defensive approach but it allows for portability. If you wanted to extract your logic into a module for reuse, you may want to check if the object exists as well or risk unwanted errors from an area of the application which you might not necessarily be concerned with.
这是一种更具防御性的方法,但它允许可移植性。如果您想将您的逻辑提取到一个模块中以供重用,您可能需要检查该对象是否也存在,或者冒着来自您可能不一定关心的应用程序区域的不必要错误的风险。
回答by Nishanth Matha
if you want to check both obj and prop exists (like you mentioned in your comments) you have to do:
如果您想检查 obj 和 prop 是否存在(就像您在评论中提到的那样),您必须执行以下操作:
if(obj && obj.hasOwnProperty('some'))
or if(obj && obj.some)
if(obj && obj.hasOwnProperty('some'))
或者 if(obj && obj.some)
As mentioned in comments this will throw error if obj is undefined. A better comparison would be would be:
如评论中所述,如果 obj 未定义,这将引发错误。更好的比较是:
if(typeof obj != "undefined" && obj.hasOwnProperty('some'))
回答by adonike
You could do something like:
你可以这样做:
if(user.session && 'email' in user.session) //do something...
in case you're sure that user is defined.
如果您确定用户已定义。