JS Testing Properties 判断属性是否在对象里的方法
TestingProperties
Tocheckwhetheranobjecthasapropertywithagivenname.Youcandothiswiththeinoperator,withthehasOwnProperty()andpropertyIsEnumerable()methods,
在JS中判断一个对象是否包含某个属性,可以使用in,hasOwnProperty()andpropertyIsEnumerable()
orsimplybyqueryingtheproperty.
或者直接使用查询属性。
in--Itreturnstrueiftheobjecthasanownpropertyoraninheritedproperty
用In,当前对象存在或者有继承,就返回true。
hasOwnProperty()--Totestwhetherthatobjecthasanownpropertywiththegivenname.Itreturnsfalseforinheritedproperties
用hasOwnProperty(),只关心本对象,不关心继承来的属性。
propertyIsEnumerable()--ThepropertyIsEnumerable()refinesthehasOwnProperty()test.Itreturnstrueonlyifthenamedpropertyisanownpropertyanditsenumerableattributeistrue.
用propertyIsEnumerable(),和hasOwnProperty()这个类似,只是要求属性可枚举。
Insteadofusingtheinoperator itisoftensufficienttosimplyquerythepropertyanduse!==tomakesureitisnotundefined
o.x!==undefined;//true:ohasapropertyx
替代In的最简单办法就是 query + !==Undefined
incandistinguishbetweenpropertiesthatdonotexistandpropertiesthatexistbuthavebeensettoundefined.
in有个好处就是还能区分到底属性的值是undefined还是本身就不存在。
以上这篇JSTestingProperties判断属性是否在对象里的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。