if(键入对象)或if(object.hasOwnProperty(key) [英] if (key in object) or if(object.hasOwnProperty(key)

查看:174
本文介绍了if(键入对象)或if(object.hasOwnProperty(key)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下两个语句是否产生相同的输出?有没有理由更喜欢另一种方式?

Do the following two statements produce the same output? Is there any reason to prefer one way to the other?

 if (key in object)

 if (object.hasOwnProperty(key))


推荐答案

小心 - 它们不会产生相同的结果。

Be careful - they won't produce the same result.

in 也将返回 true 如果在原型链的某处找到 key ,而 Object.hasOwnProperty (就像名字已告诉我们的那样),只返回 true 如果 key 直接在该对象上可用(它拥有该财产)。

in will also return true if key gets found somewhere in the prototype chain, whereas Object.hasOwnProperty (like the name already tells us), will only return true if key is available on that object directly (its "owns" the property).

这篇关于if(键入对象)或if(object.hasOwnProperty(key)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆