1.in方法:检测当前对象是否存在某个属性(不管当前这个属性是对象的私有属性还是公有属性,只要有结果就是true)
let obj = {name: 'fjl'}
console.log('name' in obj) // true
console.log('toString' in obj) // true
2.hasOwnProperty方法:检测当前对象是否存在某个私有属性(必须时私有的属性)
let obj = {name: 'fjl'}
console.log(obj.hasOwnProperty('name')) // true
console.log(obj.hasOwnProperty('toString')) // false
3.使用Object.keys()
let obj = {name: 'fjl'}
Object.keys(obj).includes('name') // true
Object.keys可以拿到对象的属性值并合并为一个对象进行返回,再使用includes方法进行检测即可。
练习
创建一个检测当前属性是否为对象公有属性的方法,与hasOwnProperty相反
function hasPubProperty(obj, att) {
if(att in obj) {
if(!obj.hasOwnProperty(att)) {
return true
}else {
return false
}
}else {
alert("既不是私有,也不是公有")
}
}
console.log(hasPubProperty({name: "name"}, "age"))