hasOwnProperty表示是否有自己的属性。这个方法会查找一个对象是否有某个属性,但是不会去查找它的原型链。
// 利用 typeof 获取变量的类型
// 利用 hasOwnProperty 判断 对象自身属性中是否具有指定的属性,具有则返回 true,否则则是 false
let a = 1;
console.log(typeof (a));
let b = {
age: 18,
sex: 'male',
a: {
b: 1,
c: {
d: 'swwwww',
s:false
}
}
}
console.log(typeof (b));
console.log(b.hasOwnProperty('age'));
console.log(b.hasOwnProperty('sex'));
console.log(b.hasOwnProperty('a'));
console.log(b.a.hasOwnProperty('b'))
console.log(b.a.c.hasOwnProperty('s'))
console.log(typeof (b.a.c.d))
输出:
number
object
true
true
true
true
true
string
一般在枚举的时候常用。书中的枚举指的主要是: 遍历一个对象并且获取该对象自身的所有属性。
遍历可以直接通过 forIn 循环执行,而判断是否为对象自身属性,则需要借助 hasOwnProperty 方法