一 、在JavaScript中,有几种方法可以判断对象属性是否存在:
-
使用
in
操作符:property in object
例如:'name' in obj
,如果obj
对象有name
属性,返回true
,否则返回false
。 -
使用
hasOwnProperty()
方法:object.hasOwnProperty(property)
例如:obj.hasOwnProperty('name')
,如果obj
对象有name
属性且该属性是它自己的,返回true
,否则返回false
。 -
使用
typeof
操作符:typeof object.property !== 'undefined'
例如:typeof obj.name !== 'undefine