zl程序教程

您现在的位置是:首页 >  前端

当前栏目

【javascript】hasOwnProperty()方法检查对象是否有该属性

JavaScript属性方法对象 是否 检查 hasOwnProperty
2023-06-13 09:11:14 时间

hasOwnProperty() 只会检查对象的自有属性,对象原形上的属性其不会检测;但是对于原型对象本身来说,这些原型上的属性又是原型对象的自有属性,所以原形对象也可以使用hasOwnProperty()检测自己的自有属性

上面的解释有点拗口

看下面的代码就能理解

let obj = {
    name:'张睿',
    age:18,
    eat:{
        eatname:'面条',
        water:{
            watername:'农夫山泉'
        }
    }
}
console.log(obj.hasOwnProperty('name')) //true
console.log(obj.hasOwnProperty('age'))  //true
console.log(obj.hasOwnProperty('eat'))  //true
console.log(obj.hasOwnProperty('eatname'))  //false
console.log(obj.hasOwnProperty('water'))  //false
console.log(obj.hasOwnProperty('watername'))  //false
console.log(obj.eat.hasOwnProperty('eatname'))  //true
console.log(obj.eat.hasOwnProperty('water'))  //true
console.log(obj.eat.hasOwnProperty('watername'))  //false
console.log(obj.eat.water.hasOwnProperty('watername'))  //true